1

我在页面上有一个表单,它通过 jQuery 将新数据添加到数据库中。它工作正常,但有时服务器会崩溃,我得到一个500 (Internal Server Error),但那是因为我的服务器很糟糕。

问题是我有时会在 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.');
  }
});
4

2 回答 2

0

您可以将 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;
};

但最好的办法是修复服务器..这些东西只是弥补另一个问题的黑客和补丁:坏的服务器。:)

因此,对于任何生产场景来说,这都不是一个好主意。

于 2011-01-05T14:24:39.170 回答
0

如果添加返回错误,您可以创建插入数据库的控件。

   ...
   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();
          }
        });              
   }
   ...
于 2011-01-05T14:33:17.550 回答