jQuery AJAX请求事件 - 完成,失败,成功 [英] jQuery AJAX request events - done,fail,success

查看:338
本文介绍了jQuery AJAX请求事件 - 完成,失败,成功的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有类似的代码

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
            });

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

It is working no problem. My question is why this doesnt work:

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
            }
        });

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

Fail and done are just examples, complete also doesnt work if used inside. But using it outside like:

ajaxrequest.complete(f(){});

工作得很好......我知道我应该使用成功而不是完成,但那不是我的指向这里。
这里有什么交易?

is working just fine... I know instead of done I should use success, but thats not my point here. Whats the deal here?

推荐答案

你需要使用成功和错误是你需要使用的方法,如果你想要使用你的第二个选项

you need to use success and error is the method you need to use if you want to use your second option

这是没有承诺的ajax请求的例子,你获得成功和错误函数作为参数

this is example of ajax request without promise, where you are getting success and error function as parameter

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






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


In the first opetion you are using promise object return by ajax requst that is the reason you are getting done and fail method.

这是promise对象的示例,在下面的示例请求是promise对象

this is example of promise object , in below example request is promise object

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 );
});

这篇关于jQuery AJAX请求事件 - 完成,失败,成功的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆