2011-07-19 56 views
0

您好所有我有这样的代码的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执行后未定义......如果我把警报(临时)继续怎么回事?我怎样才能把温度值继续下去?

在此先感谢!

回答

3

这是因为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 
} 
0

您提供的$.getJSON()函数的回调函数。直到请求完成才会执行。