个性化阅读
专注于IT技术分析

如何执行许多ajax请求并使用jQuery $ .ajax仅在1个回调中获得结果

你是否曾经尝试过向服务器发出多个Ajax请求?如果你不知道如何正确处理它们(干净的代码, 可维护性等), 则此任务将变得非常混乱。对于”初学者”, 以下示例可以解决问题:

注意:在此示例中, 为了防止CORS请求错误, 我们在每个原始URL之前使用cors-anywhere URL, 你需要使用自己的URL:

var $requestUrlExample = "https://cors-anywhere.herokuapp.com/http://jsfiddle.net/api/user/ourcodeworld/demo/list.json";
var $requestUrlTwo = "https://cors-anywhere.herokuapp.com/http://jsfiddle.net/api/user/ourcodeworld/demo/list.json?start=1&limit=1";
var $requestUrlThree = "https://cors-anywhere.herokuapp.com/https://api.github.com/repos/sdkcarlos/artyom.js";

$.getJSON($requestUrlExample, function(resp1){
    $.getJSON($requestUrlTwo, function(resp2){
        $.getJSON($requestUrlThree, function(resp3){
            // Here all the responses will be available
            console.log(resp1);
            console.log(resp2);
            console.log(resp3);
        });
    });
});

它的工作原理是, 记住一个简单的分层请求示例”如果它是愚蠢的并且它有效, 那不是愚蠢”。但是, 有一种更干净的方法来实现多个请求并仅通过一个回调处理它们。

在这种情况下, 我们将使用$ .when函数, when提供了一种基于零个或多个对象执行回调函数的方法, 这些对象通常代表延迟事件的Deferred对象。如果没有参数传递给jQuery.when(), 它将返回一个解决承诺。如果将单个Deferred传递给jQuery.when(), 则该方法将返回其Promise对象(Deferred方法的子集)。

在下面的示例中, 我们将对json格式的不同url执行3个json请求, 并且仅用1个回调即可处理所有内容。

var $requestUrlExample = "https://cors-anywhere.herokuapp.com/http://jsfiddle.net/api/user/ourcodeworld/demo/list.json";
var $requestUrlTwo = "https://cors-anywhere.herokuapp.com/http://jsfiddle.net/api/user/ourcodeworld/demo/list.json?start=1&limit=1";
var $requestUrlThree = "https://cors-anywhere.herokuapp.com/https://api.github.com/repos/sdkcarlos/artyom.js";

$.when($.getJSON($requestUrlExample), $.getJSON($requestUrlTwo), $.getJSON($requestUrlThree)).then(function (resp1, resp2, resp3) {
    // The request reponse will be retrieven respectively of the given order
    // Response structure : [responseContent, strinStatus("sucess" or "error"), xhrObject]
    console.log(resp1); // to retrieve the real content use resp[0]
    console.log(resp2);
    console.log(resp3);
}).fail(function (problem) {
    // handle errors (some request has failed)
    console.log(problem);
});

显然, 如果1个请求失败, 那么你将无法检索其他请求的结果, 而是使用when能够处理错误。播放以下包含先前代码的小提琴(导航至”结果”选项卡):

使用when函数可使你的代码更简洁, 更紧凑。从jQuery V1.5开始, 此功能可用。你可以在此处阅读有关when函数的更多信息。

请注意, 你也可以使用$ .ajax({url:” mypath”})对象, 而不仅仅是$ .get, $ getJSON或$ .post函数。玩得开心 !

赞(0)
未经允许不得转载:srcmini » 如何执行许多ajax请求并使用jQuery $ .ajax仅在1个回调中获得结果

评论 抢沙发

评论前必须登录!