我有增加了新的数据,以通过jQuery数据库的页上的形式。它工作正常,但有时服务器胡扯了,我得到的 500(内部服务器错误)的,但那是因为我的服务器太烂。

的问题是,我有时会收到服务器错误的PHP使得除了数据库后,而是获得成功的消息,我得到的错误,即使除了已经取得进展。所以,我应该怎么去是为了确保如果我得到错误的PHP不添加数据?

[是的,我最终将转换到新的服务器,但没有服务器是完美]

这里的脚本:

$.ajax({
  type: "POST",
  url: "/clase/do-add",
  data: $("#add").serialize(),
  dataType: "json",
  timeout: 8000,
  beforeSend: function() {
    var icon = '<p class="loading-add"></p>'; // loading icon
    $('form#add').append(icon);
  },
  success: function(data) {
    if (data.error == true) { // php returns error = true if name is invalid
      alert('Invalid name.');
      $('form#add').find('p').remove();
    } else {
      // make the addition
    }
  },
  error: function () { 
    $('form#add').find('p').remove();
    alert('Error. Try again.');
  }
});
有帮助吗?

解决方案

您可以再次错误包你Ajax调用的函数和“传请求”的功能。

东西林克这样:

jQuery.fn = function yourajaxfunction(){
    $.ajax({
      type: "POST",
      url: "/clase/do-add",
      data: $("#add").serialize(),
      dataType: "json",
      timeout: 8000,
      beforeSend: function() {
        var icon = '<p class="loading-add"></p>'; // loading icon
        $('form#add').append(icon);
      },
      success: function(data) {
        if (data.error == true) { // php returns error = true if name is invalid
          alert('Invalid name.');
          $('form#add').find('p').remove();
        } else {
          // make the addition
        }
      },
      error: function () { 
        $('form#add').find('p').remove();
        // ####### i added this:
        $(this).yourajaxfunction();
        alert('Error. Try again.');
      }
    });
}

或者你可以有一个闲置的功能再次检查一些毫秒之后,您就再次在错误运行函数之前:

$(this).idle().yourajaxfunction();

上面使用空闲功能:

jQuery.fn.idle = function(time){
    var o = $(this);
    o.queue(function(){
       setTimeout(function(){
          o.dequeue();
       }, time);
    });
    return o;
};

但最好的事情是修复服务器..这东西只是黑客和补丁弥补了另一个问题:糟糕的服务器。 :)

因此,这不是一个好主意,任何生产场景。

其他提示

可以在创建插入到数据库的控制,若添加返回的错误的。

   ...
   error: function () { 
        var fError = function() {

             $('form#add').find('p').remove();
             alert('Error. Try again.');

            };

       $.ajax({
          type: "GET",
          url: "/clase/do-check",
          data: {id: id}, // id for check
          dataType: "json",
          success: function(data) {
            if (!data.ok)
               fError();
          },
          error: function () { 
               fError();
          }
        });              
   }
   ...
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top