我无法将元素推送到工作数组。控制台日志返回正确的对象,但它们不会被推送到数组...这是我的代码:
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
});
关于Javascript推送方法不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10249946/