开发者

getJson problem, it returns undefined

开发者 https://www.devze.com 2023-03-21 02:30 出处:网络
hello all i have this code var temp; if(method==1) temp = $(\"#Words\").val();//get the words from textbox

hello all i have this code

var temp;
if(method==1)
  temp = $("#Words").val();             //get the words from textbox
else{
  $.getJSON("http://localhost/mine/test.js", function(data) {
      temp=data.Words;
  });
}
//do something with temp...but temp is undefined after the execution of else

but temp is undefined after the executi开发者_Python百科on of getJson...if i put an alert(temp) it continues whats going on? how can i take the value of temp to continue?

thanks in advance!


it's because getJSON is ajax request, not synchronous. Try this

var temp;
if(method==1) {
  temp = $("#Words").val();             //get the words from textbox
  proc(temp);
} else {
  $.getJSON("http://localhost/mine/test.js", function(data) {
      temp=data.Words;
      proc(temp);
  });
}

function proc(data){
    //do something with temp...but temp is undefined after the execution of else
}


you are providing the $.getJSON() function with a callback function. That doesn't get executed until the request is complete.

0

精彩评论

暂无评论...
验证码 换一张
取 消