2016-11-28 51 views
1

林有一个小问题,使这项工作:jQuery的,JSON阵推

这里是我的JSON数组通过AJAX拉:

{ 
    "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返回数组,但我无法推送它。

+0

的执行console.log可能发生的GET请求完成之前,尝试将超时,以测试它是否工作。 – jmona789

+0

添加oncomplete节并将console.log放在那里。 – nurdyguy

回答

3

使用index, value$.each回报:

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

注:$.each().each()不同。

希望这会有所帮助。

+0

好的,我现在看到我的问题。如果我放置console.log(项目);在ajax中获取,然后我可以看到结果,但我希望能够访问ajax调用之外的项目数组。 – Alko

+0

是的,你不能立即访问结果,因为'$ .get()'是异步的,请看看[如何从异步调用返回响应?](http://stackoverflow.com/questions/ 14220321 /如何-DO-I-返回的响应,从-的异步调用)。 –

2

您需要将params传递给$.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>