2011-12-19 130 views
0

我试图使用jQuery get()函数发出HTTP GET请求,但我遇到了一些麻烦。从jQuery发出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

任何人都可以建议我怎么处理这个?

非常感谢!

+0

'String(temp)'做了什么? – 2011-12-19 22:29:33

+0

哪里是'bdy'定义? – muratgu 2011-12-19 22:31:22

+0

就同步问题而言,为什么不使用jQuery推迟链接回调? – JesseBuesking 2011-12-19 22:35:03

回答

0

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

如需帮助采用上述模块,看到我的跟进问题here

0

构造bdy在所有页面被检索后,即商店get产生字典或数组;等待所有get s完成;然后按照正确的顺序组装它们。

+0

我想到了这一点,但我觉得应该有一些内置的方式来做到这一点,这是我希望在这里找到的 – efficiencyIsBliss 2011-12-19 22:40:23

0

我想这个和它的作品:

// 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); 
     }); 

}); 
+0

我得到了与以前一样的代码的相同结果。 – efficiencyIsBliss 2011-12-19 22:39:41

0

至于什么@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个异步下载,然后在全部完成时通知您。