2011-07-19 55 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()函數的回調函數。直到請求完成纔會執行。