如何将AJAX成功变量存储为AJAX之外的变量? [英] how to store AJAX success variable as variable outside of AJAX?

查看:83
本文介绍了如何将AJAX成功变量存储为AJAX之外的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用AJAX来获取名为变量myPubscore的数据.现在,我正在尝试将myPubscore发送到另一个js文件. myPubscore在Ajax中可以正常打印,但是当我在sendResponse之前打印时,出现事件处理程序中的错误:ReferenceError:未定义myPubscore".

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".

如何将myPubscore退出AJAX并发送到sendResponse?我通读了有关此问题的另一篇SO帖子,但受访者提到答案已经贬值了.

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

更新了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);
        });

推荐答案

在使用$.ajaxfetchXMLHttpRequest之类的异步调用时,其回调将在以后的[很远]点运行.周围范围已经运行,因此您需要使用回调内的调用结果,如

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?

在Chrome中,onMessage API事件无法识别侦听器返回的Promise,因此要异步使用sendResponse,您需要从onMessage侦听器返回true并在ajax回调中调用sendResponse:

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

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关键字注释

请注意,返回true时,您不能使用async关键字标记onMessage侦听器,因为它实际上会将Promise对象返回给API,Chrome扩展API不支持该对象.在这种情况下,请使用单独的异步函数或异步IIFE,示例.

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.如果您使用 WebExtension polyfill ,则可以从onMessage侦听器返回一个Promise并使用async直接充当侦听器.在Firefox中,API可以直接使用.

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.

这篇关于如何将AJAX成功变量存储为AJAX之外的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆