jQuery的递延不工作 [英] jQuery Deferred not working

查看:138
本文介绍了jQuery的递延不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了code为

function search(query) {
    var dfr = $.Deferred();
    $.ajax({
        url: "http://search.twitter.com/search.json",
        data: {
            q: query
        },
        dataType: 'jsonp',
        success: dfr.resolve
    });
    return dfr.promise();
}

Test = {
    start: function(){
        alert("Starting");
    }
};

function gotresults(data) {
    alert(data.max_id);
}

function showDiv() {
    $('<div />').html("Results received").appendTo('body');
}

$.when(search('ashishnjain'))
    .then(gotresults)
    .then(showDiv);

这工作正常。然而,当我把它写成:

This works as expected. However when I write it as:

Test.start()
    .then(search('ashishnjain'))
    .then(gotresults)
    .then(showDiv);

它只是提醒启动和terminates.A工作的例子可以在 http://jsfiddle.net找到/ XQFyq / 2 / 。我究竟做错了什么?

it just alerts "Starting" and terminates.A working example can be found at http://jsfiddle.net/XQFyq/2/. What am I doing wrong?

推荐答案

测试不是的延期对象,因此它不具有法的 。那么() 。当() 延迟对象因此,为什么当你调用它的作品。当()

Test is not a deferred object, so it does not have a method .then(). .when() IS a deferred object hence why it works when you call .when().

$。阿贾克斯()通话的延期对象,因此,如果您返回,作为你的'Test.start()方法的一部分,您可以添加 。那么() 回调的看到这里例子)的,在的 。那么() 回调会被调用一次Ajax调用已经解决,即已经恢复它的数据,然而,这是不是真的正确使用延迟的对象,我不觉得。下面是更它是如何旨在用于我相信:

Your $.ajax() call IS a deferred object, so if you return that as part of your 'Test.start() method, you can add .then() callbacks (see example here), the .then() callbacks will be called once the ajax call has been resolved, i.e. has returned its data, however this isn't really the correct use of the deferred object I don't think. The following is more how it is intended to be used I believe:

function searchTwitter(query){
    $.ajax({
            url: "http://search.twitter.com/search.json",
            data: {
                q: query
            },
            dataType: 'jsonp',
            success: function(data){return data;}
        })
        .then(gotresults)
        .then(showDiv)
        .fail(showFailDiv);
};

function gotresults(data) {
    alert(data.max_id);
}

function showDiv() {
    $('<div />').html("Results received").appendTo('body');
}

function showFailDiv() {
    $('<div />').html("Results <b>NOT</b> received").appendTo('body');
}

// Starting can be done with a click:

$("#searchTwitter").click(function(){
   searchTwitter($("#searchName").val()); 
});

// OR a static call:
searchTwitter("ashishnjain");

查看它的工作 这里

如果你想在例如 showDiv()将其更改为 showDiv返回的数据(数据) .. ......

If you want the returned data in for example showDiv() change it to showDiv(data).....

下面是如何,你可以创建自己的推迟对象,而不是另一个例子依托href="http://api.jquery.com/category/deferred-object/" rel="nofollow">推迟的对象 阿贾克斯()的通话。这是一点点接近你原来的例子 - 如果你想看到它失败的例子,将URL更改为 http://DONTsearch.twitter.com/search.json 例如这里 的:

Here is another example of how you could create your own deferred object instead of relying on the deferred object of the .ajax() call. This is a little closer to your original example - if you want to see it fail for example, change the url to http://DONTsearch.twitter.com/search.json example here:

var dfr;

function search(query) {
    $.ajax({
        url: "http://search.twitter.com/search.json",
        data: {
            q: query
        },
        dataType: 'jsonp',
        success: function(data){dfr.resolve(data);},
        error:  function(){dfr.reject();}
    });
}

Test = {
    start: function(){
        dfr = $.Deferred();
        alert("Starting");
        return dfr.promise();        
    }
};


function gotresults(data) {
    alert(data.max_id);
}

function showDiv() {
    $('<div />').html("Results received").appendTo('body');
}

function showFailDiv() {
    $('<div />').html("Results <b>NOT</b> received").appendTo('body');
}

Test.start()
    .then(search('ashishnjain'))
    .then(gotresults)
    .then(showDiv)
    .fail(showFailDiv);


更新回答的评论:


Update to answer the comments:

在您版本11 ,您讲的不是一个失败的延迟的对象,所以它永远不会调用 .fail()回调。为了改善这种情况,可以使用AJAX跨pretation如果 .fail()错误:....... 的通知的失败错误的递延对象:drf.reject - 这将运行。失败()回调。

In your version 11, you are not telling the deferred object of a failure, so it will never call the .fail() callback. To rectify this, use the ajax interpretation if the .fail() (error:.......) to advise the deferred object of a failure error: drf.reject - this will run the .fail() callback.

至于你所看到的原因相册更多>> code()跑直线距离,在。那么()呼叫回调,如果你传递一个字符串,再像函数presentation:。然后(ShowDiv)一次轮到它回调将寻找该名称的功能。如果你传递一个函数调用。然后(someMore code('阿希什'))它将运行功能。试试吧,将。然后(showDiv)。然后(showDiv())你会尽快通知code运行时,它会显示从 showDiv的code()

As for the reason you are seeing ShowMoreCode() run straight away is, the .then() calls are callbacks, if you pass it a string representation of a function like: .then(ShowDiv) once its turn comes the callback will look for a function with that name. If you pass a call to a function .then(someMoreCode('Ashish')) it will run the function. Try it, change .then(showDiv) to .then(showDiv()) you will notice as soon as the code runs, it will show the code from showDiv().

如果您更改。然后(相册更多>> code('阿希什'))。然后(相册更多>> code),您可以从 $。阿贾克斯()调用访问返回的数据。像这样的:

If you change .then(ShowMoreCode('Ashish')) to .then(ShowMoreCode), you can access the returned data from the $.ajax() call. Like this:

function someMoreCode(name) {
    alert('Hello ' + name.query);
}

看看这里:工作和的不工作 .fail()

这篇关于jQuery的递延不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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