我正在从我的 popup.html
进行 AJAX 调用,如下所示..
chrome.extension.sendRequest(
{
req: "send",
url: requrl
},
function(response)
{
console.log("RESPONSE:" + response.reply);
});
这段代码适用于background.html中的以下情况...
case "send":
sendResponse({
reply: send(request.url)
});
break;
这又调用以下...
function send(uri)
{
var xhr = new XMLHttpRequest();
xhr.open("POST",uri,true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
xhr.onreadystatechange = function (send){
if(xhr.readyState == 4){
return xhr.responseText;
}
}
xhr.send(null);
}
我的问题是,在 send()
有机会响应之前,我的代码返回了 undefined
。如何让我的代码等待响应?我需要保持此调用异步,因为我需要不卡住 UI 来显示进度对话框。
最佳答案
您收到 undefined
的原因是这是 send
函数的结果。如果您按原样查看该函数,您会发现它在 send(null)
之后退出。 return 语句要在一段时间后才会执行,到那时就没有任何东西可以接收它了。
如果您想在 XHR 请求完成时进行响应,则需要使用回调。
简而言之:
case "send:"
send(request.url, function(response) {
sendResponse(response);
})
function send(uri, callback) {
...
xhr.onreadystatechange = function (send){
if(xhr.readyState == 4){
callback(xhr.responseText);
}
}
...
}
关于javascript - Chrome 扩展 : Why is my response returning before the AJAX call?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6015895/