访问函数外部的局部变量?

时间:2022-04-17 12:57:45

I'm getting data from a PHP file, and as an example, storing a variable that uses that data. It's stored within two functions:

我从PHP文件中获取数据,例如,存储使用该数据的变量。它存储在两个函数中:

$("#image1").on("click",function(){

    $(".click").one("click",function(){

        $.getJSON("getnew.php",function(data){
        var img1 = data.img1;

Then I have to post it to another PHP file, which is only stored within the first function.

然后我必须将它发布到另一个PHP文件,该文件仅存储在第一个函数中。

$("#image1").on("click",function(){

// above stuff is first

    $.post("update.php",
        {img1link: img1}

but I can't access the img1 variable since it's local within the other function.

但我无法访问img1变量,因为它在其他函数中是本地的。

2 个解决方案

#1


0  

All you have to do is remove the var from var img1 = data.img1; declaration.

您所要做的就是从var img1 = data.img1中删除var;宣言。

If you use var the variable will be declared in the local scope. If u just declare the variable without a var, it will be declared in the global scope

如果使用var,则变量将在本地范围内声明。如果你只是声明没有var的变量,它将在全局范围内声明

#2


-1  

It's not a good practice to use global variables in any programming language. So I will recommend you to make use of saving context before going into ajax call. Like-

在任何编程语言中使用全局变量都不是一个好习惯。因此,我建议您在进入ajax调用之前使用保存上下文。喜欢-

$("#image1").on("click",function(){

    $(".click").one("click",function(){

        $.getJSON("getnew.php",function(data){
        var img1 = data.img1;
        var self=this; // This is saving current context in self variable.
       $.post("update.php",
        {img1link: self.img1} //here you can access that variable using self.

#1


0  

All you have to do is remove the var from var img1 = data.img1; declaration.

您所要做的就是从var img1 = data.img1中删除var;宣言。

If you use var the variable will be declared in the local scope. If u just declare the variable without a var, it will be declared in the global scope

如果使用var,则变量将在本地范围内声明。如果你只是声明没有var的变量,它将在全局范围内声明

#2


-1  

It's not a good practice to use global variables in any programming language. So I will recommend you to make use of saving context before going into ajax call. Like-

在任何编程语言中使用全局变量都不是一个好习惯。因此,我建议您在进入ajax调用之前使用保存上下文。喜欢-

$("#image1").on("click",function(){

    $(".click").one("click",function(){

        $.getJSON("getnew.php",function(data){
        var img1 = data.img1;
        var self=this; // This is saving current context in self variable.
       $.post("update.php",
        {img1link: self.img1} //here you can access that variable using self.