我正在使用 Tastypie 创建一个 API,我想从 Backbone 访问该 API。 要发送凭据,我使用 user_id 和 api_key。我在 android 中使用 curl 执行此操作,效果很好,但我可以从 Backbone 设置 http header 。
在 curl 中我使用:
curl --dump-header - -H "Accept: application/json" -H "Content-Type: application/json" -H "user_id: 32" -H "api_key: 69950" -X DELETE "http://127.0.0.1:8000/api/v1/deletenote/66/?format=json"
在 android java 中我使用:
HttpDelete requestDELETE = new HttpDelete();
requestDELETE.setHeader("Content-type", "application/json");
requestDELETE.setHeader("Accept", "application/json");
requestDELETE.setHeader(Constants.HEADER_USER_ID, user_id);
requestDELETE.addHeader(Constants.HEADER_API_KEY, key);
它们都工作得很好,但是当我按照我在该页面的其他帖子中找到的回复在 Backbone 中尝试此操作时,这没有用。
我正在尝试:
var removeNote = new DeleteNoteModel({id:this.model.toJSON().id},{ query:this.model.toJSON().id});
removeNote.destroy({
headers: {'user_id':dataWeb.get("id"),'api_key':dataWeb.get("api_key")}
},{
async:false,
error: function(model, response){
console.log("KO_REMOVE_NOTE");
console.log(response);
},
success : function(model, response){
console.log("OK_REMOVE_NOTE");
console.log(response);
}
}
);
我在调用 destroy 调用时放置了 header ,但这不会向服务器发送任何内容。
我在错误的模式下做什么?
感谢大家。
最佳答案
Tallmaris 的回答应该会为您解决这个问题,但我建议您使用 jQuery ajaxSetup将 header 设置为所有 ajax 请求的默认值的方法,因为我相信您一直都需要它们,对吗?
启动应用程序的地方
$.ajaxSetup({
headers: {
'user_id':dataWeb.get("id"),
'api_key':dataWeb.get("api_key")
}
});
多亏了它,你会省去很多重复的代码 :) 保持干爽!
(显然,您需要确保 dataWeb 在您启动应用程序的范围内可用:))
关于http - 在主干中放置一个自定义的 http header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13074349/