Javascript推送方法不起作用

标签 javascript json jquery

我无法将元素推送到工作数组。控制台日志返回正确的对象,但它们不会被推送到数组...这是我的代码:

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/

相关文章:

javascript - 在 javascript 中掷骰子

javascript - GSON 不是对象错误

jquery - 使用 jQuery 匿名上传图像到 Imgur API v3?

JavaScript 将数组作为单个参数传递给函数

javascript - jquery 同级 ('.class' 的奇怪错误)在我的例子中

javascript - TypeError : Object. 条目不是函数

javascript - 如何在页面加载后淡入: Javascript

javascript - 如何在不重新加载页面的情况下对数据进行分页?

Python 请求 - 从 response.text 中提取数据

javascript - $.ajax 结合 $.ajaxSetup 默认设置