function get_message(params) {
var messages = ["hello", "bb"]; // i have manually assigned the value here for testing purpose
$.getJSON("messages.json", function( json ) {
var test="JSON Data: " + json.login.loginsuccess.excited.en[0] ; // this is working fine. just retrieving 1 value for testing
console.log(test); // it shows the output get from json file. this line is also fine
messages.push(test);// here is the problem. why i am not being able to add value to this array messages?
});
alert(messages[2]);// it gives me out put undefined
var index = Math.floor(Math.random() * messages.length);
return messages[index];
}
感谢
答案 0 :(得分:0)
这是因为AJAX调用是异步的,因此在将数据推送到messages数组之前会触发alert()行。尝试移动代码以在回调函数中显示警报。
答案 1 :(得分:0)
getJson
是异步的,因此您需要确保不要过早检查消息数组。您应该使用回调来获取所需的信息。
function get_message(params, callback) {
var messages = ["hello", "bb"];
$.getJSON("messages.json", function( json ) {
var test="JSON Data: " + json.login.loginsuccess.excited.en[0];
console.log(test);
messages.push(test);
alert(messages[2]);
var index = Math.floor(Math.random() * messages.length);
callback(messages[index]);
});
}
并使用如下:
get_message(params, function (data) {
console.log(data);
});