简单的jquery ajax响应错误

Jas*_*vis 3 php jquery

几个问题,首先使用下面的var字符串,1个工作但我需要让第二个工作,有一个snytax错误,因为我不知道如何写它

var string = 'id='+ id ;
var string = 'id='+ id 'USER=1';
Run Code Online (Sandbox Code Playgroud)

第二; 这个ajax调用下面,它发布到delete.php删除注释,它工作但我想添加一些错误处理.一旦我将它添加到后端,我怎么能让它在jquery中显示错误?

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

kar*_*m79 9

你错过了一个连接运算符和一个&符号,我也不会使用'string'作为变量名:

var str = 'id='+ id + '&USER=1';
Run Code Online (Sandbox Code Playgroud)

也就是说,"字符串"不是JS保留字,但看起来仍然是不好的做法(至少对我来说).

你在'string'变量中传递给$ .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();   
    }
   }
  });
Run Code Online (Sandbox Code Playgroud)