Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
583 views
in Technique[技术] by (71.8m points)

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

I have the following function:

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

jQuery.post("my/path/somefile.php", { instance: 'getUrl', ID : id, type: type},
function(data)
{ 
    jQuery('#logo').attr("src",data.url + img);
},"json"); 
  1. How can I get the value of img when I'm inside the function?
  2. How can I sett img = new value from inside the function?

UPDATE

This code does NOT give a new value to the variable:

    logoUrl = "noLogo.png";

    jQuery.post("my/path/somefile.php", { instance: 'getUrl', ownerID : "123", type: "brand"},
    function(logo)
    {
        logoUrl = logo.url + "logo/";
    },"json");      

    alert(logoUrl); // This outputs noLogo.png"
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...