【问题标题】:Simple jquery ajax response on error错误时的简单 jquery ajax 响应
【发布时间】:2009-08-10 23:30:47
【问题描述】:

几个问题,首先是下面的这个 var 字符串,第一个有效,但我需要让第二个有效,因为我不知道如何编写,所以有一个语法错误

var string = 'id='+ id ;
var string = 'id='+ id 'USER=1';

第二; 下面这个 ajax 调用,它发布到 delete.php 以删除评论,它可以工作,但我想添加一些错误处理。将其添加到后端后,如何使其在 jquery 中显示错误?

$.ajax({
   type: "POST",
   url: "delete.php",
   data: string,
   cache: false,
   success: function(){
    commentContainer.slideUp('slow', function() {$(this).remove();});
    $('#load').fadeOut();
  }

【问题讨论】:

    标签: php jquery


    【解决方案1】:

    您缺少连接运算符和 & 符号,我也不会使用“字符串”作为变量名:

    var str = 'id='+ id + '&USER=1';
    

    也就是说,'string' 不是 JS reserved word,但似乎仍然是不好的做法(至少对我而言)。

    您在“字符串”变量中传递给 $.ajax 的是一个查询字符串,我建议您阅读以下内容以获取更多信息:

    http://en.wikipedia.org/wiki/Query_string

    关于错误处理的问题,一种方法是检查响应文本并采取相应措施,例如:

    $.ajax({
       type: "POST",
       url: "delete.php",
       data: string,
       cache: false,
       success: function(resp){
        if(resp == 'error') { //get PHP to echo the string 'error' if something bad happened
            alert('There was an error!');
        } else {
            commentContainer.slideUp('slow', function() {
                $(this).remove();
            });
            $('#load').fadeOut();   
        }
       }
      });
    

    【讨论】:

    • 看起来它可以完美运行,虽然属性列表后缺少 },但我现在得到 1 个错误,这是错误 = });
    • @jasondavis - 成功块未正确关闭 - 我已编辑,请重试。
    【解决方案2】:

    对于第二个问题,你是指HTTP错误还是服务器端代码错误?

    如果你的意思是一个 HTTP 错误,就像“成功”一样,有一个可以调用的“错误”

    请参阅文档here

    【讨论】:

    • 我的意思是我自己的错误,比如如果用户在 x 时间内发布到许多 cmets,我想将错误代码发送回 jquery 到浏览器以显示消息而不是返回作为成功
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-12
    • 1970-01-01
    相关资源
    最近更新 更多