gpt4 book ai didi

javascript - 来自服务器的 Json 数据未填充主干模型

转载 作者:行者123 更新时间:2023-11-30 18:09:13 25 4
gpt4 key购买 nike

我是 Backbone.js 和 Require.js 的新手 我正在尝试从服务器获取数据并将其存储在我的 Backbone 模型中。问题是数据没有填充模型。

require.config({
paths:{
jquery:"libs/jquery-1.7.1.min",
underscore:"libs/underscore-min",
backbone:"libs/backbone-min",
models:"models",
views:"views",
collections:"collections"
},
shim:{
"backbone":{
"deps":["underscore","jquery"],
"exports":"Backbone"
},
"underscore":{
"exports":"_"
}
}
});


require (['routes'],function() {
new Router ();
});

模型

define (['jquery','underscore','backbone'],function($,_,Backbone){
Video = Backbone.Model.extend ({
defaults:{
video_id:'',
video_name:'',
},
urlRoot:"/video",
});
});//end define

路由器

define(['backbone','models/Video'],function(Backbone){
Router = Backbone.Router.extend({
routes:{
"/":"index",
},
initialize:function (){
this.index ();
},
index:function ()
{
video = new Video ({id:"1Uw6ZkbsAH8"});
video.fetch();
console.log (video.toJSON());
}
});
});//end define

我检查了网络响应,我得到了“{video_id:1,video_name:test_backbone}”作为响应,但是当我使用 console.log (video.toJSON()) 时,我得到了 - Object {id: "1Uw6ZkbsAH8", video_id:“”,video_name:“”}。我做错了什么?

最佳答案

在您的代码中,日志记录是在调用 fetch 之后立即完成的。 fetch 向服务器发出异步请求以获取数据。即使在网络请求完成之前,您的日志记录调用也会立即执行。这是基于事件的编程的陷阱之一。

尝试在 success 回调中调用 console.log

video.fetch ( { 
success: console.log(video.toJSON());
}
);

关于javascript - 来自服务器的 Json 数据未填充主干模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15046893/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com