【问题标题】:jQuery, JSON array pushjQuery、JSON 数组推送
【发布时间】:2017-04-12 19:22:44
【问题描述】:

我在完成这项工作时遇到了一点问题:

这是我通过 ajax 拉取的 json 数组:

{
    "message": [{
        "title": "Account",
        "id": 1
    }, {
        "title": "Content",
        "id": 2
    }, {
        "title": "Other",
        "id": 3
    }]
}

这里是javascript:

var items = [];
$.get("settings.php", {
        getlink: 1,
    }, function(json) {
        $.each(json.message, function() {
            items.push(this);
        });

},"json");

console.log(items)

但由于某些原因,items 数组始终为空 [] 我可以在 firebug 中看到,json 返回数组,但我无法推送它。

【问题讨论】:

  • console.log 可能在获取请求完成之前发生,尝试添加超时以测试它是否有效。
  • 添加一个完整的部分并将console.log放在那里。

标签: jquery json each


【解决方案1】:

使用 $.each 返回的index, value

$.each(json.message, function(index, value) {
    items.push(value);
});

注意:$.each() 不同于 .each()

希望这会有所帮助。

【讨论】:

  • 好的,我现在看到我的问题了。如果我放置 console.log(items);在 ajax get 中,我可以看到结果,但我希望能够在 ajax 调用之外访问 items 数组。
  • 是的,您无法立即访问结果,因为$.get() 是异步的,请查看How do I return the response from an asynchronous call?
【解决方案2】:

您需要将参数传递给$.each 函数并将该对象推送到您的数组。

var json = {
    "message": [{
        "title": "Account",
        "id": 1
    }, {
        "title": "Content",
        "id": 2
    }, {
        "title": "Other",
        "id": 3
    }]
}

var items = [];
$.each(json.message, function(index, item) {
  items.push(item);
});

console.log(items)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-05
    • 1970-01-01
    • 1970-01-01
    • 2015-09-13
    相关资源
    最近更新 更多