I have the following js + jQuery code with some misbehaving var scopes…or at least a misbehaving coder :-p
var lookup_output=""; //believe this makes it a global scope
function lookupWord(word) {
var url = 'http://localhost:3000/jianti/' + word + '.json';
lookup_output = "abc";
$.getJSON(url, function(data){
$.each(data, function(i, word_data){
lookup_output += "<div> trad: " + word_data.fanti + "<br>";
lookup_output += "simp: " + word_data.jianti + "<br>" ;
lookup_output += "pinyin: " + word_data.pinyin + "<br>" ;
lookup_output += "def: " + word_data.def + "<br>" ;
lookup_output += "</div><br>";
alert(lookup_output);
});
});
lookup_output += "123";
return lookup_output;
}
the problem is that the line
return lookup_output;
gives back
"abc123"
whereas the line
alert(lookup_output);
gives
"abc123<div> trad: 交流<br>simp: 交流<br>pinyin: jiāo liú<br>def: exchange/give-and-take/to exchange/to alternate/communication/alternating current (electricity)<br></div><br>"
i want the return line to give out the same as the output…any ideas how? i thought that by attaching it to a global variable it would do it, but seems not.
You don’t have a scoping problem, you have a problem with the asynchronous nature of the
$.getJSONcall.$.getJSONis an AJAX call and the “A” in “AJAX” stands for “asynchronous”. When you call$.getJSON, it will return you’ll continue on yolookup_output += "123", then later, the$.getJSONcallback function will get called.The usual approach is to add more callbacks:
Then, you’d call it like this: