【问题标题】:Send back not empty xmlhttprequest [duplicate]发回不为空的xmlhttprequest [重复]
【发布时间】:2019-01-25 20:03:46
【问题描述】:

为什么 sendResponse({ helloWorld: sendto }) 发回空字符串而不是 this.responseText 分配给 sendto 变量?如何正确管理我的代码以实现返回 this.responseText 而不是空字符串?

chrome.runtime.onMessage.addListener(

        function (request, sender, sendResponse) {
            **var sendto = 'empty';**
            var ccc = new XMLHttpRequest();
            ccc.onreadystatechange = function () {
                if (this.readyState == 4 && this.status == 200) {
                    console.log(this.responseText)
                    **sendto = this.responseText;**




                }
            }
            ccc.open("GET", "http://127.0.0.1:3000/" + request.greeting)
            ccc.send();

            **sendResponse({ helloWorld: sendto });**

        });

【问题讨论】:

  • 在监听函数末尾添加return true;,以提供异步响应。
  • 它不会工作......
  • 尝试发布的答案

标签: javascript google-chrome-extension xmlhttprequest


【解决方案1】:

您需要将return true; 添加到侦听器函数中才能异步使用sendResponse。例如:

chrome.runtime.onMessage.addListener(

    function (request, sender, sendResponse) {
        var ccc = new XMLHttpRequest();
        ccc.onreadystatechange = function () {
            if (this.readyState == 4 && this.status == 200) {
                console.log(this.responseText)
                sendResponse({helloWorld: this.responseText});
            }
        };

        ccc.open("GET", "http://127.0.0.1:3000/" + request.greeting)
        ccc.send();

        return true;  // in order to use sendResponse asynchronously

    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-02-25
    • 2017-07-13
    • 2017-11-22
    • 1970-01-01
    • 2018-08-19
    • 2015-02-25
    • 2018-07-12
    • 2018-09-08
    相关资源
    最近更新 更多