how to store AJAX success variable as variable outside of AJAX?

╄→尐↘猪︶ㄣ 提交于 2020-06-23 16:52:39

问题


I used AJAX to get data that I named variable myPubscore. Now I'm trying to send myPubscore to another js file. myPubscore prints fine in Ajax, but when I print just before sendResponse, I get "Error in event handler: ReferenceError: myPubscore is not defined".

How do I get myPubscore out of AJAX and into sendResponse? I read through another SO post on this problem, but the respondents mentioned that the answer had depreciated.

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"});
    }

updated 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);
        });

回答1:


When using an asynchronous call like $.ajax or fetch or XMLHttpRequest, its callback runs at a [much] later point in the future when the surrounding scope already ran so you need to use the results of the call inside the callback as explained in How do I return the response from an asynchronous call?

Important addition for extension messaging in Chrome

In Chrome, the onMessage API event won't recognize a Promise returned by the listener so to be able to use sendResponse asynchronously you need to return true from the onMessage listener and call sendResponse in the ajax callback:

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.type === 'articleUrl') {
    $.ajax({
      url: '...........',
      success(data) {
        sendResponse(data);
      },
    });
    return true;
  }
});

or

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
  if (request.type === 'articleUrl') {
    fetch('https://www.example.org').then(r => r.text()).then(sendResponse);
    return true;
  }
});

async keyword note

Note that you can't mark the onMessage listener with the async keyword when returning true because it would actually return a Promise object to the API, which is not supported in Chrome extensions API. In this case use a separate async function or an async IIFE, example.

P.S. If you use WebExtension polyfill you can return a Promise from the onMessage listener and use async function as a listener directly. In Firefox this is how the API works out-of-the-box.



来源:https://stackoverflow.com/questions/61787586/how-to-store-ajax-success-variable-as-variable-outside-of-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!