调用函数中声明的变量

call a variable that is declared within a function

本文关键字:变量 声明 函数 调用      更新时间:2023-09-26

我在chrome扩展中使用消息传递将数据从background.js移动到content.js文件。

在下面的函数中,当我将变量输出到函数中的控制台时,我会得到我期望的数据。当我在函数外尝试相同的操作时,我会得到null(如全局变量中定义的)。

有人知道我如何从函数中提取数据,这样我就可以用AJAX调用发布它吗。

代码

var capturedData = "url=" + window.location.href;
var localHash = "localhash=" + CryptoJS.MD5(capturedData);
var email = null;
chrome.extension.sendMessage({greeting: "hello"}, function(response) {
    email = response;
    console.log(JSON.stringify(email));
    return true;
});
console.log(JSON.stringify(email));

$.ajax({
    type: 'post',
    url: 'url',
    data: {"url":capturedData, "localhash":localHash},
    dataType: 'json',
    success : function (data) {
        if(data.url)
        {
            console.log(data.url);
        }  
    }
});

输出

null content.js:10{"电子邮件":"email@email.com"}content.js:7

谢谢!

您需要在电子邮件上获得一些值后进行ajax调用:

var capturedData = "url=" + window.location.href;
var localHash = "localhash=" + CryptoJS.MD5(capturedData);
var email = null;
chrome.extension.sendMessage({greeting: "hello"}, function(response) {
    email = response;
    console.log(JSON.stringify(email));

$.ajax({
    type: 'post',
    url: 'url',
    data: {"url":capturedData, "localhash":localHash},
    dataType: 'json',
    success : function (data) {
       if(data.url)
       {
        console.log(data.url);
       }  
    }
 });
return true;
});
 console.log(JSON.stringify(email));