jQuery AJAX请求事件 - 完成,失败,成功

zma*_*ric 5 javascript ajax jquery request

我有这样的代码

var ajaxrequest = $.ajax({
            type: "POST",
            dataType: "json",
            url: "xy.php", 
            data: {
                action : "read"
            }
            }).fail(function(){
                //something to do when ajaxreq fails
            }).done(function(data){

               //something to do when ajaxreq is done
            });
Run Code Online (Sandbox Code Playgroud)

它没有问题.我的问题是为什么这不起作用:

var ajaxrequest = $.ajax({
            type: "POST",
            dataType: "json",
            url: "n3_vaje_api.php", //Relative or absolute path to response.php file
            data: {
                action : "read",
            },
            fail:function(){
                //something to do when ajaxreq fails
            },
            done:function(data){
              //something to do when ajaxreq is done
            }
        });
Run Code Online (Sandbox Code Playgroud)

失败和完成只是示例,如果在内部使用完成也不起作用.但在外面使用它像:

ajaxrequest.complete(f(){});
Run Code Online (Sandbox Code Playgroud)

工作得很好......我知道我应该使用成功而不是完成,但这不是我的观点.什么交易在这里?

Pra*_*ana 7

您需要使用成功,如果您想使用第二个选项,则需要使用错误

这是没有承诺的ajax请求的示例,其中您获得成功并将错误函数作为参数

 $.ajax({url:"demo_test.txt"
      ,error : function (xhr,status,error)
        { //alert error}
      ,success:function(result){
      $("#div1").html(result);
    }});
Run Code Online (Sandbox Code Playgroud)

在第一个操作中,您使用promise对象返回ajax requst,这是您完成和失败方法的原因.

这是promise对象的示例,在下面的示例中,request是promise对象

var request = $.ajax({
  url: "script.php",
  type: "POST",
  data: { id : menuId },
  dataType: "html"
});

request.done(function( msg ) {
  $( "#log" ).html( msg );
});

request.fail(function( jqXHR, textStatus ) {
  alert( "Request failed: " + textStatus );
});
Run Code Online (Sandbox Code Playgroud)