【发布时间】:2018-06-10 16:40:03
【问题描述】:
我正在使用 JQuery 在 WordPress 环境中链接 ajax 调用以访问第三方 API。
工作流程是这样的,我首先得到一个对象数组,每个对象都有一个start_date 和end_date。然后我需要使用这些参数进行 ajax 调用,并将响应与原始参数相关联。我还需要一一处理 ajax 请求,因为它们都立即加载并不重要,我想控制网络请求(页面上加载了很多其他资产)。
无论如何,这是我的代码:
var superobjects; //variable to hold final result - want the response and the original date params in this array of objects
var callback = function(result) {
superobjects.push(result); //callback of ajax request using jQuery.when
};
var requests = []; // array to hold requests before doing them one at a time with jQuery.when
for (i = 0; i < data.length; i++) {
requests.push(jQuery.ajax({
url: wpApiSettings.root + 'superplugin/v1/superdooperendpoint/' + api_key + "/" + data[i].start_date + "/" + data[i].end_date,
method: 'GET',
beforeSend: function(xhr) {
// Set nonce here
xhr.setRequestHeader('X-WP-Nonce', wpApiSettings.nonce);
},
done: function(data) {
console.log({
start_date: data[i].start_date,
end_date: data[i].end_date
});
//this console.log above never fires
}
}));
}
setTimeout(function() {
console.log(superobjects) //no request information here!
}, 2222);
jQuery.when.apply(undefined, requests).then(function(result) {
callback(result) //run the ajax sequentially and then do the callback - problem is I've lost the request params here!
});
您可能知道,当我在日志中执行superobjects 时,它没有来自我用来创建请求的start_date 或end_date 的任何信息,只是阿贾克斯调用。无论如何,仍然有这个顺序的 ajax 工作流并且仍然在我的最终superobject 中获得请求参数吗?我猜有巧妙地使用函数和范围,但我现在看不到它,所以正在寻求帮助! :)
【问题讨论】:
-
如果
done的登录从未显示,听起来请求失败了。添加错误处理程序并找出原因。还可以检查浏览器开发工具网络中的实际请求。一旦你解决了这个问题,就需要做更多的重组,但先让这部分工作,然后应该会看到新的错误 -
@charlietfl 我不认为这是正确的......该请求必须被触发,因为当我
console.log()为superobjects它填充了新的响应以及我看到它网络标签。 -
jQuery.ajax()不接受done选项。它确实接受success选项,或者您可以链接jQuery.ajax(...).done(successHandler)。但是,在实践中,您都不应该这样做。相反,链jQuery.ajax(...).then(successHandler, [errorHandler])。.then()方法具有成功选项或.done()方法所不具备的宝贵额外功能。 -
@Roamer-1888 好的,但是鉴于我想如何调用 Ajax,如何在承诺响应中获取请求参数?
标签: javascript jquery ajax promise