horizon使用的是backbone框架,可是咱們的後臺api都是隻接收post請求,請求的路徑爲/api/,根據backbone的官檔解釋:html
backbone的model.save方法會判斷當前的model對象是否存在存在服務器中,若是存在服務器中,則調用"update" (HTTP PUT), 若是不存在,則調用"create" (HTTP POST), 判斷的依據即爲當前的model的屬性'id'是否存在。ajax
舉例以下:api
var UpdateAgentV = ModalView.extend({ initialize: function(data) { this.model = new UpdateAgentM(); this.setDefault(); this.defaults.id = 'edit-agent'; this.defaults.header = translate('operations.edit'); this.renderModal(); this.model.bind('change', this.render, this); this.model.set({ agents_id: data.project_id }); this.getAgent(data.project_id); }, getAgent: function(project_id){ var $this = this; this.ajaxRequest({ action: 'GetAgentsDetail', project_id: project_id }, function(res){ $this.model.set({ account_bank: res.data.account_bank, account_name: res.data.account_name, account_number: res.data.account_number, url: res.data.url, logo: res.data.logo, company: res.data.company, }); }); }, render: function() { tpl = _.template($("#template-edit-agent").html()); this.defaults.body = tpl(this.model.toJSON()); this.$el.html(this.template(this.defaults)); $('.modal-dialog').draggable({ handle: "div.modal-header" }); return this; }, }); var UpdateAgentM = ModalModel.extend({ defaults: { action: 'UpdateAgents', agents_id: '', account_bank: '', account_name: '', account_number: '', url: '', logo: '', company: '', }, initialize: function() { this.validator(); }, validator: function() { $("#edit-agent").find("form").validate({ rules: { account_bank: { required: true }, account_name: { required: true }, account_number: { required: true }, url: { required: true }, logo: { required: true }, company: { required: true }, } }); }, create: function(element) { var data = this.formSerialize(element); this.set(data); this.saved(agentsView); } });
上例中若將UpdateAgentV的initialize的this.model.set({agents_id: data.project_id});改成this.model.set({id: data.project_id});, 則在model調用save方法時則會認爲當前的model已經存在,提交數據就會用PUT方法。服務器