Javascript推送方法不工作
我无法将元素推送到works数组。控制台日志正在返回正确的对象,但它们不会被推送到阵列。。。这是我的密码:Javascript推送方法不工作,javascript,json,jquery,Javascript,Json,Jquery,我无法将元素推送到works数组。控制台日志正在返回正确的对象,但它们不会被推送到阵列。。。这是我的密码: var works = new Array(); $(window).ready(function() { $.getJSON('AJAX/getWorks.php', function(data) { $.each(data, function(key, val) { console.log(v
var works = new Array();
$(window).ready(function()
{
$.getJSON('AJAX/getWorks.php', function(data) {
$.each(data, function(key, val) {
console.log(val);
works.push(val);
});
});
console.log(works);
});
和json对象:
Object
date: "2012-04-08 17:53:58"
description: "sadasd"
id: "2"
link: "sadasd"
name: "dsad"
objects: null
position: "2"
__proto__: Object
有人知道我做错了什么吗?提前感谢您的回答…您在代码中过早地记录了数组。
console.log
将在ajax请求完成之前运行,因为ajax
是异步的
$.getJSON('AJAX/getWorks.php', function(data) {
$.each(data, function(key, val) {
console.log(val);
works.push(val);
});
console.log(works); // move this here so the array is logged after the ajax request finishes.
});
编辑
如果希望在ajax请求之后使用该变量,可以执行以下操作
创建一个函数来容纳ajax请求
function getWorks()
{
return $.getJSON('AJAX/getWorks.php', function(data) {
$.each(data, function(key, val) {
works.push(val);
});
}
然后,您可以执行以下操作以确保ajax请求已完成
$.when( getWorks() ).then(function(){
// you can access the array in here because the ajax has finished executing
});
缺少的右括号是复制/粘贴错误吗?如何知道它们不在数组中?在哪里输出阵列?您确定在ajax请求完成之前没有记录数组吗?如果您将调试语句更改为
console.log(val,works)
?是的,数据是数组,val是对象…是的,OP中的记录代码在ajax调用完成之前运行。不,我不这么认为。。。我在document.ready中记录,就在getJson函数之后,所以对象必须已经初始化…没有人看我的示例吗?!你们这些人真是难以置信!这个示例减去JSON(无法正确测试),并包含全局变量。嘘,谢谢,这就是我要找的!当…然后。。。我错过了那部分!谢谢!