我想在Backbone.js的REST服务的帖子请求中添加标题,我尝试两种方式:
this.model.save( { headers: {'X-Token' : myToken } } );
并使用setResquestHeader:
功能:
sendToken: function (xhr) {
var tokenCookie;
var name = "xtoken" + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++)
{
var c = ca[i].trim();
if (c.indexOf(name)==0) tokenCookie = c.substring(name.length,c.length);
}
xhr.setRequestHeader('X-Token', tokenCookie);
}
电话:
this.model.save({
beforeSend: this.sendToken,
success: function() {
alert("success");
},
error: function(model,response,options) {
alert("error");
}
});
但它似乎不起作用,它不发送标题
答案 0 :(得分:3)
Model.save
的签名为model.save([attributes], [options])
。您必须传递属性的空/空哈希才能添加选项:
this.model.save(null, {
headers: {'X-Token' : 'myToken'}
});
演示http://jsfiddle.net/nikoshr/a4gss/
或
this.model.save(null, {
beforeSend: function(xhr) {
xhr.setRequestHeader('X-Token', 'set token');
}
});