2011-07-19 6 views
0

こんにちは、私はこのコードgetJsonの問題は、それが未定義

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の価値をどのように受け継ぐことができますか?

ありがとうございます!

答えて

3

これはgetJSONが同期ではなくajaxリクエストであるためです。あなたがコールバック関数で$.getJSON()機能を提供している。この

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

を試してみてください。要求が完了するまで実行されません。

関連する問題