使用jQuery进行GET请求的问题

Problems making GET request from jQuery

本文关键字:问题 请求 GET jQuery 进行 使用      更新时间:2023-09-26

我试图使用jQuery get()函数进行HTTP GET请求,但我遇到了一些麻烦。

下面是我的代码:
// get the links on the page
var pageLinks = $.find('#pageLinks');
// loop through each of the links
$(pageLinks).find('a').each(function(){
   if($(this).attr('title') !== "Next Page"){
       // make a GET request to the URL of this link
   $.get($(this).attr("href"), function(data) {
           console.log("here");
           var temp = parse_page(data);
           // concatenate the return string with another
           bdy = bdy+String(temp);
           console.log("done");
       });
   }
});

我需要从多个页面获取数据。由于get()函数是异步的,所以我以随机顺序获得页面。其次,串联不起作用。即使我得到了每一页,它们也没有放到bdy中。

谁能建议我如何处理这个问题?

非常感谢!

在检索所有页面后构建bdy,即将get结果存储在字典或数组中;等待所有get完成;然后按正确的顺序组装。

我试了这个,它工作:

// get the links on the page
var pageLinks = $('a');
var bdy 
// loop through each of the links
$(pageLinks).each(function(){
console.log(this);
       // make a GET request to the URL of this link
           $.get($(this).attr("href"), function(data) {
           // concatenate the return string with another
           bdy = bdy + data.toString();
           console.log(bdy);
       });
});

作为@muratgu所说的一个例子:

var results = [];
var count = 0;
function allDone() {
    var bdy = results.join("");
    // do stuff with bdy
}
// get the links on the page
var pageLinks = $.find('#pageLinks');
// filter the links so we're left with the links we want
var wantedLinks = $(pageLinks).find('a').filter(function (idx) {
    return $(this).attr('title') !== "Next Page";
});
// remember how many links we're working on
count = wantedLinks.length;
// loop through each of the links
wantedLinks.each(function (idx) {
    // make a GET request to the URL of this link
    $.get($(this).attr("href"), function (data) {
        console.log("here");
        var temp = parse_page(data);
        results[idx] = temp;
        // Decrement the count.
        count--;
        if (count === 0) {
            // All done.
            allDone();
        }
    });
});

您可以进一步将其抽象为可以执行N个异步下载的数据类型,然后在所有下载完成时通知您。

我刚刚发现有一些模块允许在JS中管理控制流。我找到的是:

  • 异步

有关使用上述模块的帮助,请参阅我的后续问题。