In jQuery.post, how do I get value of variable outside function?

前端 未结 2 1518
醉梦人生
醉梦人生 2020-12-20 05:40

I have the following function:

var id = \"10\";
var type = \"Type A\";
var img = \"myimage.jpg\";

jQuery.post(\"my/path/somefile.php\", { instance: \'getUrl         


        
相关标签:
2条回答
  • 2020-12-20 06:27

    You should be able to do exactly what you have there - globals are visible inside functions unless there's already a local variable of the same name declared.

    0 讨论(0)
  • 2020-12-20 06:38

    UPDATE

    When working with callback functions, its important to pay attention to execution flow:

    var img = "nice.jpg";
    
    $.post('/path', { key: value }, function(data){
       img = "newname.jpg";
    });
    
    alert(img); // Alerts "nice.jpg"
    

    It is because any code occurring after the callback (but not in the callback function) is executed first:

    1. Set img to nice.jpg
    2. Call $.post
    3. Call alert
    4. Set img to newname.jpg

    Original answer:

    If the code you are using exists exactly as you posted it, then:

    1. img is already available inside your anonymous callback function.
    2. Yes, you can change the value of img from inside the function as well.

    When you declare variable with the var keyword, it is private to its current scope, but is available to any other contexts contained within its scope:

    WORKS

    function getPost(){
       var img = "nice.jpg";
    
       $.post('/path', {key:value}, function(data){
           alert(img); // alerts "nice.jpg"
       });
    }
    

    DOES NOT WORK

    function changeImage(){
       var img = "nice.jpg";
       getPost();
    }
    
    function getPost(){
       $.post('/path', {key:value}, function(data){
           alert(img); // img is undefined
       });
    }   
    
    0 讨论(0)
提交回复
热议问题