Basic jquery deferred usage with ajax

Basic jquery deferred usage with ajax

本文关键字:with ajax usage deferred jquery Basic      更新时间:2023-09-26

我正在尝试重写代码 如何将异步 ajax 响应捕获到变量中? 以使用 jquery 延迟函数。我从 :

    var html ="";
    $.ajax({
                        type:"POST",
                        url: "Ajax/getHtml",
                        data: { u : contents },
                        dataType: 'html',       
                        success: function(data) {
                            html = data;
                        },
                        error: function(jqXHR, textStatus, errorThrown) {
                                console.log('error');
                                console.log(jqXHR,textStatus, errorThrown);
                        }
                    });
                     console.log('html', html); 

我正在尝试将其转换为延迟函数,可以在返回请求的 html 页面时解决。我一直在阅读 http://learn.jquery.com/code-organization/deferreds/examples/,http://jqfundamentals.com/chapter/ajax-deferreds 这样做。到目前为止,我已经想出了:

                    var html_response = new $.Deferred(url){
                    $.ajax({
                            type:"POST",
                            url: "Ajax/getHtml",
                            data: { u : url},
                            dataType: 'html',       
                            success: html_response.resolve,
                            error: html_response.reject
                        });
                    };

这将用作 :

                    html_response().done{
                         console.log('html', html);
                   }

我正在尝试做的是当get_html函数成功返回html(即get_html解析)时,抓取html并将其发送到控制台。我很难弄清楚如何在这里将这些碎片放在一起。有人可以建议我吗?

你正在做的事情有正确的概念。如果我理解正确,您正在尝试做一些"真正的异步"ajax,这与上一篇文章不同。

您错误地执行的一件事是解析延迟的 jQuery 变量。

正确的代码应如下所示:

           var html_response = $.Deferred();    // no need for new
           function get_html(url){
                $.ajax({
                        type:"POST",
                        url: "Ajax/getHtml",
                        data: { u : url},
                        dataType: 'html',       
                        success:function(data) {
                            html_response.resolve(data);  //resolve is a fn
                        },
                        error: function(x, status, err) {
                            html_response.reject(err);    //reject is a fn
                        }
                    });
                };
           }
           get_html(inserturlhere);
                html_response.done(function(html){       // handle success
                     console.log('html:   ' + html);
                })
                .fail(function(error) {                 // handle failure
                    console.log(error);
                });

但是,ajax 已经明确地带有延迟,所以一定要先检查一下。 http://api.jquery.com/jquery.ajax/

这是有效的,因为 $.ajax 返回了它自己的承诺(如动画),从而消除了创建自己的延迟对象的需要。

function html_response(url){
  return $.ajax({
    //ajax stuff
  });
}
html_response(url).done(function(data){
  console.log(data);
});

这里不需要完整的Deferred。您只需要一个Promise,其界面是Deferred界面的子集(有关更多信息,请参阅 Deferred 上的文档)。promise 有一个方法.done(),允许您提供在异步进程成功结束时执行的回调。

$.ajax() 方法返回一个 jqXHR 对象,该对象方便地实现Promise接口:

$.ajax() 从 jQuery 1.5 开始返回的 jqXHR 对象实现了 承诺接口,为他们提供所有属性、方法和 承诺的行为

所以当你打电话给$.ajax时,你已经有了承诺。只需做:

$.ajax({
    ...
}).done(function(data){
    console.log(data);
});

或者,如果你真的想处理一个完整的Deferred对象,你可以做:

var defr = $.Deferred();
defr.done(function(data){
    console.log(data);
});
$.ajax({
    ...
    ,sucCess : function(data){
        defr.resolve(data);
    }
});