从 json 文件向 javascript 数组添加值
Adding value to javascript Array from json file
你能告诉我我在这里做错了什么吗? 我知道它的问题很简单,但为此花了一整天的时间。我试图做的只是向数组添加一个名为 JSON 文件的消息的值。
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];
}
谢谢
这是因为 AJAX 调用是异步的,所以 alert() 行在数据推送到消息数组之前触发。 尝试移动代码以在回调函数中显示警报。
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);
});
相关文章:
- 向多维数组添加值和从多维数组请求值
- 如何将JS数组添加到Meteor自动表单条目中
- 在不使用循环的情况下,从一个数据库字符串值向javascript数组添加多个对象
- 将行从数组添加到谷歌图表
- 从不同的数组添加重复的图块 PIXI.js
- 如何在 Javascript 中向数组添加其他对象
- 将javascript数组添加到多维数组中
- Coderbyte数组添加解决方案--For循环与For循环
- Knockout.js向数组添加新项
- Highcharts将变量数组添加到序列中
- 向javascript对象数组添加值
- 我可以用Javascript向数组添加函数吗
- 将数组添加到另一个数组
- 你能给被劫持的JavaScript数组添加一个函数吗
- 我可以向数组添加对象键吗
- 如何向JSON数组添加新属性
- 通过将$resource查询数组添加到AngularJS中另一个数组的底部来进行分页加载
- 使用名称/值从 json 数组添加项
- Javascript数组添加 - 所有组合
- 从 json 文件向 javascript 数组添加值