Javascript 如何将AJAX成功变量存储为AJAX之外的变量?
我使用AJAX获取我命名为变量myPubscore的数据。现在我正试图将myPubscore发送到另一个js文件。myPubscore在Ajax中打印得很好,但当我在sendResponse之前打印时,会得到“事件处理程序中的错误:ReferenceError:myPubscore未定义” 如何使myPubscore脱离AJAX并进入sendResponse?我读了另一篇关于这个问题的SO帖子,但受访者提到答案被低估了Javascript 如何将AJAX成功变量存储为AJAX之外的变量?,javascript,ajax,google-chrome-extension,Javascript,Ajax,Google Chrome Extension,我使用AJAX获取我命名为变量myPubscore的数据。现在我正试图将myPubscore发送到另一个js文件。myPubscore在Ajax中打印得很好,但当我在sendResponse之前打印时,会得到“事件处理程序中的错误:ReferenceError:myPubscore未定义” 如何使myPubscore脱离AJAX并进入sendResponse?我读了另一篇关于这个问题的SO帖子,但受访者提到答案被低估了 chrome.runtime.onMessage.addListener(f
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.type == "articleUrl") {
console.log("background heard articleUrl")
console.log(request);
var articleUrl = request;
$.ajax({
type: 'POST',
url: `${url}/buttoncolor`,
data: articleUrl,
success: function urlFunction(data) {
var myPubscore = data;
console.log("myPubscore in ajax:")
console.log(myPubscore);
}
})
console.log("myPubscore in sendresponce:")
console.log(myPubscore);
sendResponse({score: "myPubscore"});
}
更新的background.js
chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
if (request.type == "articleUrl") {
console.log("background heard articleUrl")
console.log(request);
var articleUrl = request;
$.ajax({
type: 'POST',
url: `${url}/buttoncolor`,
data: articleUrl,
success(data){
console.log("incoming data");
console.log(data);
sendResponse(data);
console.log("sent data");
},
});
return true;
}
content.js
chrome.runtime.sendMessage({ "type": "articleUrl", "url": url }, function (response) {
console.log("here's the response for sending the URL");
console.log(response);
});
当使用异步调用(如
$.ajax
或fetch
或XMLHttpRequest
)时,其回调将在以后的某个点运行,而周围的作用域已经运行,因此您需要在回调中使用调用的结果,如中所述
Chrome中扩展消息的重要补充
在Chrome中,onMessage API事件不会识别侦听器返回的承诺,因此要能够异步使用sendResponse,您需要从onMessage侦听器返回true
,并在ajax回调中调用sendResponse:
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.type === 'articleUrl') {
$.ajax({
url: '...........',
success(data) {
sendResponse(data);
},
});
return true;
}
});
或
async
关键字注释
请注意,在返回true
时,不能使用async
关键字标记onMessage侦听器,因为它实际上会向API返回Promise
对象,这在Chrome extensions API中不受支持。在这种情况下,请使用单独的异步函数或异步IIFE
另外,如果使用,您可以从onMessage侦听器返回承诺,并直接使用
async
函数作为侦听器。在Firefox中,这就是API开箱即用的工作方式。你不能。它是异步的。您可以将整个事件包装在一个Promise
中,解析并向其传递数据,然后使用promiseInstance。然后(result=>{/*now use result*/})
,但这实际上只是一个语法技巧。谢谢,但我被禁止问这个问题?我不知道如何改进这个问题。我猜是因为已经有了一个“如此”了吧?我不知道我问的时候,我甚至不知道async是什么。我不知道,但也许你暂停了提问,因为最后几个问题是重复的。这确实是不友好的。我已经解开了这个问题,看看你现在是否可以发布问题。我可以再问一次!非常感谢。我是一个没有编码老师的初学者,所以不能使用so将非常令人失望。
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.type === 'articleUrl') {
fetch('https://www.example.org').then(r => r.text()).then(sendResponse);
return true;
}
});