我使用php实现了一个REST API。我使用backbone.js来管理html视图。我需要使用AJAX向REST API发送请求并使用骨干管理视图。但我无法解决AJAX适合这种架构的问题。我感到很困惑,因为当我点击提交按钮时,模型会更新,这意味着下面的代码会向API发出请求并更新模型和视图。为什么我需要AJAX请求,它在哪里适合,即使我查看了不同的文章和示例,我也无法理解它。如果我使用AJAX,这一行var urlstr = "API" + this.get("brand");
var Car = Backbone.Model.extend({
url: function () {
var urlstr = "API" + this.get("brand");
return urlstr;
},
defaults: {
brand: null,
imageurl: null,
year: null
}
});
var bmw = new Car();
var TestView = Backbone.View.extend( {
el: ".container",
model: bmw,
initialize: function () {
this.listenTo(this.model,"sync change", this.gotdata);
},
events: {
"click #submitbtn" : "getdata"
},
getdata: function (event) {
var brand = $('#brand').val();
this.model.set({name:brand});
this.model.fetch();
},
gotdata: function () {
var brand = this.model.get("name");
var image = this.model.get("imageurl");
var year = this.model.get("year");
$('#name').html(name);
$('#image').html(image);
$('#year').html(year);
}
}
);
var testview = new TestView();