我正在尝试通过Backbone JS获取数据,并从收到的JSON数据中获取每条记录。我尝试了很多方法,但最终总是使用Object对象,[]或来自JSON数据的一些随机字符。
var emp = Backbone.Model.extend({
urlRoot:"/api/test/employees",
initialize:function () {
}
});
var employees = new emp();
employees.fetch({
success: function (allEmployees) {
$(jQuery.parseJSON(JSON.stringify(allEmployees))).each(function() {
var ID = this.id;
var NAME = this.name;
alert(ID+ NAME);
});
}
});
API输出如下所示
[
{
"id": "10",
"firstName": "Kathleen",
"lastName": "Byrne",
"title": "Sales Representative",
"reportCount": "0"
},
{
"id": "9",
"firstName": "Gary",
"lastName": "Donovan",
"title": "Marketing",
"reportCount": "0"
},
{
"id": "7",
"firstName": "Paula",
"lastName": "Gates",
"title": "Software Architect",
"reportCount": "0"
},
{
"id": "11",
"firstName": "Amy",
"lastName": "Jones",
"title": "Sales Representative",
"reportCount": "0"
},
{
"id": "6",
"firstName": "Paul",
"lastName": "Jones",
"title": "QA Manager",
"reportCount": "0"
},
{
"id": "1",
"firstName": "James",
"lastName": "King",
"title": "President and CEO",
"reportCount": "4"
},
{
"id": "3",
"firstName": "Eugene",
"lastName": "Lee",
"title": "CFO",
"reportCount": "0"
},
{
"id": "5",
"firstName": "Ray",
"lastName": "Moore",
"title": "VP of Sales",
"reportCount": "2"
},
{
"id": "2",
"firstName": "Julie",
"lastName": "Taylor",
"title": "VP of Marketing",
"reportCount": "2"
},
{
"id": "12",
"firstName": "Steven",
"lastName": "Wells",
"title": "Software Architect",
"reportCount": "0"
},
{
"id": "4",
"firstName": "John",
"lastName": "Williams",
"title": "VP of Engineering",
"reportCount": "3"
},
{
"id": "8",
"firstName": "Lisa",
"lastName": "Wong",
"title": "Marketing Manager",
"reportCount": "0"
}
]
我在哪里做错了?如何从收到的JSON数据中记录记录?
完全像这样
{
"id": "10",
"firstName": "Kathleen",
"lastName": "Byrne",
"title": "Sales Representative",
"reportCount": "0"
}
和下一个记录,依此类推,直到最后一个,一个接一个。
答案 0 :(得分:1)
不,我正试图在上面的结构中一个接一个地将它们存取到localStorage中
我没有看到在你的情况下使用Backbone的具体原因,如果使用Backbone只是从服务器获取JSON数据为什么不使用jQuery $.getJSON()
函数?
$.getJSON('/api/test/employees', function(items) {
$.each(items, function(_, item) {
// doSomethingWith(item);
});
});
如果要使用Backbone获取数据,则应创建一个集合:
var EmployeesCollection = Backbone.Collection.extend({
url: "/api/test/employees",
model: emp
});
var Employees = new EmployeesCollection();
Employees.fetch({
success: function(collection) {
collection.each(function(model) {
// doSomethingWith(model);
});
}
})