getJson问题,返回undefined



大家好我有这段代码

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

但是在getJson执行后temp是未定义的…如果我设置一个警报(temp)它会继续发生什么?我如何获取temp的值来继续?

提前感谢!

这是因为getJSON是ajax请求,而不是同步的。试试这个

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
}

您正在为$.getJSON()函数提供回调函数。直到请求完成后才执行。

最新更新