使用jQuery进行GET请求的问题
Problems making GET request from jQuery
我试图使用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中管理控制流。我找到的是:
- 异步
有关使用上述模块的帮助,请参阅我的后续问题。
相关文章:
- 神秘的ajax json请求问题jQuery
- 遇到400错误请求(Angular+WebAPI)的问题
- 请求js中的回调问题
- 为什么我在对话框中遇到Ajax请求问题
- Ajax Asysnchronous 请求问题
- jQuery 和 Ajax 请求数据问题
- 同步 Ajax 请求将导致页面上出现任何问题
- 如何修复Chromium Portable中的跨来源请求共享问题
- Nodejs请求之后是请求同步问题
- 将JSON REST请求加载到Kendo ui列表视图中的问题
- 管道订购问题?将stdin管道化为http请求,并将结果管道化为stdout
- 如何解决等待多个请求以javascript发送响应的问题
- ajax请求上的kendo分页问题
- angular单元测试http请求问题
- AJAX请求在jQuery中获取函数,变量问题
- 在Node JS中发出GET请求的问题
- text区域高度请求滚动高度流问题
- Angular 在 http 请求后不更新页面(范围问题?
- Jquery JSON 请求的语法错误问题
- 有问题与承诺角度.控制台日志不适用于 HTTP 请求