繁体   English   中英

Chrome扩展程序:为什么我的响应在AJAX调用之前返回?

[英]Chrome-Extension: Why is my response returning before the AJAX call?

我正在通过我的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);
    }
  }
  ...
}

cf 其他异步回调问题

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM