使用 json 数据填充现有数组
Populate existing array with json data
我用 JSON 返回的数据填充现有数组几乎没有什么麻烦。这是我所拥有的
myarr=[];
function fillarr()
{
$.getJSON("test.php?c=10",function(data)
{
$.each(data, function(key, val)
{
myarr.push(data[val]);
}
});
});
}
我的问题是,数组在函数之外是emty。请帮忙。
myarr=[];
function fillarr()
{
$.getJSON("test.php?c=10",function(data)
{
$.each(data, function(key, val)
{
myarr.push(val);
console.log(myarr); // you will myarr here, not out side
}
});
});
console.log(myarr); // wont get
}
myarr
ajax 请求完成后获取其内容并花费时间。 所以console
在请求完成之前执行 $.getJSON 之外。
myarr=[];
function fillarr()
{
$.getJSON("test.php?c=10", function(data) {
$.each(data, function(key, val) {
myarr.push(val);
});
doSomethingNowThatTheArrayIsActuallyPopulated();
});
}
fillarr();
console.log(myarr); // This will print an empty array, it hasn't been populated yet.
function doSomethingNowThatTheArrayIsActuallyPopulated() {
console.log(myarr); // This will print the array which now contains the json values
}
如果返回数据是一个对象,则更容易执行jQuery.each将每个值推送到数组。
function fillarr(){
$.getJSON("test.php?c=10",function(data){
$.each(data, function(key, val){
myarr.push(val);
});
});
}
如果返回数据是数组,则数组连接会更快
function fillarr(){
$.getJSON("test.php?c=10",function(data){
myarr = myarr.concat(data);
});
}
相关文章:
- 将数据推送到数组填充 jqGrid
- 使用 JSON 数组填充输入字段
- 用Javascript中的JSON数组填充HTML
- 动态生成的表格 - 使用数组填充TD值
- 使用数组填充if语句值
- AngularJS:用两个JSON数组填充复选框列表,最初检查了一个数组中的一些项
- 为什么不是't ng表将数据从数组填充到表中
- 在javascript中用数组填充对象
- 高图表 - 从数组填充数据
- 如何从下拉列表中由可观察数组填充的选定项中检索完整对象
- 使用 JavaScript 数组填充下拉选择框
- Javascript array.length 为 0,但数组填充了 40 个项目
- 使用 JSON 数组填充图表
- 数组填充外部函数 - 不可访问的成员
- 用 javascript 数组填充 struts2 select 标签
- 用服务器数组填充 jquery 数组
- 如何使用 json 数组填充 Rails 下拉菜单
- 在用数组填充初始化的数组上使用数组映射的意外行为
- JavaScript 风格的数组填充在 Java 中
- 如何使用 javascript 数组填充 html 标题