Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/72.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 用jQuery'链接ajax请求;推迟_Javascript_Jquery_Jquery Deferred - Fatal编程技术网

Javascript 用jQuery'链接ajax请求;推迟

Javascript 用jQuery'链接ajax请求;推迟,javascript,jquery,jquery-deferred,Javascript,Jquery,Jquery Deferred,我有一个web应用程序,它必须多次调用服务器。到目前为止,我有一个很长的嵌套回调链;但是我想使用jQuery的when,then等功能。然而,在使用then之后,我似乎无法让东西再次运行 $ .when ($.get('pages/run-tool.html')) .then (function (args) { // This works fine alert(args); $('#content').replaceWith (args); $('#progre

我有一个web应用程序,它必须多次调用服务器。到目前为止,我有一个很长的嵌套回调链;但是我想使用jQuery的
when
then
等功能。然而,在使用
then
之后,我似乎无法让东西再次运行

$
.when ($.get('pages/run-tool.html'))
.then (function (args)
{
    // This works fine
    alert(args);
    $('#content').replaceWith (args);
    $('#progress-bar').progressbar ({value: 0});
})
.then ($.get('pages/test.html'))
.done (function(args)
{
    // This prints the same as the last call
    alert (args);
});
我做错了什么?我想这是一些范围问题,因为我可以看到第二个
get
调用正在执行。使用两个不同的
args
变量没有帮助,因为传递给done函数的参数仍然是第一个
get
请求。

所有三个回调(两个带有
然后带有
的回调和一个带有
完成的回调
的回调)都应用于相同的请求–调用时的原始
。这是因为
然后
返回相同的延迟对象,而不是新的延迟对象,因此可以添加多个事件处理程序

你需要改用

作为更新:

使用现代jquery(1.8+)时,您不需要初步的when,因为get返回一个延迟的承诺

此外,管道也不推荐使用。改用then。只需确保返回新get的结果,该结果将成为后续then/*done*/fail调用所附加的承诺

因此:


我的方法是应用回调函数:

A(function(){
       B(function(){
            C()})});
var urls = [{
    url: 'url1',
    data: 'foo'
}, {
    url: 'url2',
    data: 'foo'
}, {
    url: 'url3',
    data: 'foo'
}, {
    url: 'url4',
    data: 'foo'
}];
var requests = [];
var callback = function (result) {
    console.log('done!');
};

var ajaxFunction = function () {
    for (var request, i = -1; request = urls[++i];) {
        requests.push($.ajax({
            url: request.url,
            success: function (response) {
                console.log('success', response);
            }
        }));
    }
};

// using $.when.apply() we can execute a function when all the requests 
// in the array have completed
$.when.apply(new ajaxFunction(), requests).done(function (result) {
    callback(result)
});
其中A,B可以写成

function A(callback)
$.ajax{
    ...
    success: function(result){
        ...
        if (callback) callback();
   }
}

这是一个非常简单和高效的AJAX链接/队列插件。它将依次执行ajax方法

它的工作原理是接受一个方法数组,然后按顺序执行它们。它在等待响应时不会执行下一个方法

/---这部分是您的代码-----------------

$(文档).ready(函数(){

}))

/---这部分是AJAX插件-----------------

$.fn.sc_ExecuteAjaxQ=函数(选项){

//?在dequence中执行一系列AJAX方法
变量选项=$.extend({
fx:[]//函数1(){},函数2(){},函数3(){}
},选项);
如果(options.fx.length>0){
var i=0;
$(this.unbind('ajaxComplete');
$(此).ajaxComplete(函数(){
i++;
如果(i
}


var promise1=功能(){
还新
$.Deferred(函数(def){
setTimeout(函数(){
控制台日志(“1”);
def.resolve();
}, 3000);
}).promise();
};
var promise2=功能(){
还新
$.Deferred(函数(def){
setTimeout(函数(){
控制台日志(“2”);
def.resolve();
}, 2000);
}).promise();
};
var promise3=功能(){
还新
$.Deferred(函数(def){
setTimeout(函数(){
控制台日志(“3”);
def.resolve();
}, 1000);
}).promise();
};
var firstCall=函数(){
console.log(“firstCall”);
$.when(promise1())
.then(函数(){secondCall();});
};
var secondCall=函数(){
console.log(“第二次调用”)
$.when(promise2()).then(函数(){thirdCall();});
};
var thirdCall=函数(){
console.log(“thirdCall”)
$.when(promise3()).then(函数(){console.log(“done”);});
};
$(文档).ready(函数(){
firstCall();
});

我想我会把这个小练习留给任何可能觉得有用的人,我们构建一个请求数组,当它们完成时,我们可以启动一个回调函数:

A(function(){
       B(function(){
            C()})});
var urls = [{
    url: 'url1',
    data: 'foo'
}, {
    url: 'url2',
    data: 'foo'
}, {
    url: 'url3',
    data: 'foo'
}, {
    url: 'url4',
    data: 'foo'
}];
var requests = [];
var callback = function (result) {
    console.log('done!');
};

var ajaxFunction = function () {
    for (var request, i = -1; request = urls[++i];) {
        requests.push($.ajax({
            url: request.url,
            success: function (response) {
                console.log('success', response);
            }
        }));
    }
};

// using $.when.apply() we can execute a function when all the requests 
// in the array have completed
$.when.apply(new ajaxFunction(), requests).done(function (result) {
    callback(result)
});

cdr给出的答案是不正确的。cdr目前的得票率最高

如果函数a、b、c各自返回一个$.Deferred()对象,并按如下方式链接函数:

a().then(b).then(c)
一旦从a返回的承诺得到解决,b和c都将运行。由于这两个then()函数都与a的承诺相关联,因此其工作原理与其他Jquery链接类似,例如:

$('#id').html("<div>hello</div>").css({display:"block"})
这里,函数c的调用与函数b返回的承诺相关联

您可以使用以下代码对此进行测试:

function a() {
    var promise = $.Deferred();
    setTimeout(function() {
        promise.resolve();
        console.log("a");
    }, 1000);
    return promise;
}

function b() {
    console.log("running b");
    var promise = $.Deferred();
    setTimeout(function () {
        promise.resolve();
        console.log("b");
    }, 500);
    return promise;
}

function c() {
    console.log("running c");
    var promise = $.Deferred();
    setTimeout(function () {
        promise.resolve();
        console.log("c");
    }, 1500);
    return promise;
}

a().then(b).then(c);
a().then(function(){
    b().then(c)
});

将函数b()中的承诺从resolve()更改为reject(),您将看到不同之处。

谢谢,这很有效!只要stackoverflow允许,我就会接受:)jQuery链接对我来说仍然很可怕me@PHearst请注意,此方法现在已被弃用。Pipe是,但它不会更改语法。但是,它不使用jQuery的deferred,而且容易出现“金字塔效应”(无边界嵌套导致大量缩进)。我想这就是提问者试图避免的。cdr的答案是正确的。检查一下你的代码,为了清晰起见做了一些修改<直到
b
结束,才会调用code>c
。第二个
then
不适用于
a
承诺,但适用于
b
返回的承诺(如果它确实返回承诺,在您的示例中就是这种情况,并且在cdr响应中适用于第二个
,则
)。
a().then(b).then(c)
$('#id').html("<div>hello</div>").css({display:"block"})
a().then(function(){
    b().then(c)
});
function a() {
    var promise = $.Deferred();
    setTimeout(function() {
        promise.resolve();
        console.log("a");
    }, 1000);
    return promise;
}

function b() {
    console.log("running b");
    var promise = $.Deferred();
    setTimeout(function () {
        promise.resolve();
        console.log("b");
    }, 500);
    return promise;
}

function c() {
    console.log("running c");
    var promise = $.Deferred();
    setTimeout(function () {
        promise.resolve();
        console.log("c");
    }, 1500);
    return promise;
}

a().then(b).then(c);
a().then(function(){
    b().then(c)
});