我使用的骨干,tastypie,但我有最困难的时候得到它才能正常工作。 在Tastypie,我使用ApiKeyAuthentication我的资源,所以每一个Ajax请求,我需要的apikey和用户名追加到请求的结束或发送的用户名和API密钥添加额外的头。
我想删除一个视图和模型中使用骨干用下面的代码:
// Remove the goal update view from the DOM
removeItem: function() {
this.model.destroy({wait: true, success: function() {
console.log("success");
}, error: function() {
console.log("error");
}});
},
在函数执行后,浏览器尝试做以下网址的GET请求:
:8000/api/v1/update/2/
它不包括在最后的API_KEY或用户名,并且它在网址的结尾斜线。 我认为这是试图用Backbone.oldSync做GET请求。 我怎么会做这么同步并在末尾的用户名/ API密钥,并删除了结尾的斜线?
在所有的其它请求的,我已因此API密钥和用户名被附加到通过添加以下代码来骨架tastypie http请求的末尾:
if ( !resp && ( xhr.status === 201 || xhr.status === 202 || xhr.status === 204 ) ) { // 201 CREATED, 202 ACCEPTED or 204 NO CONTENT; response null or empty.
var location = xhr.getResponseHeader( 'Location' ) || model.id;
return $.ajax( {
url: location + "?" + "username=" + window.app.settings.credentials.username + "&api_key=" + window.app.settings.credentials.api_key,
success: dfd.resolve,
error: dfd.reject,
});
}
让我们探索的可能性
使用页眉
Backbone.sync仍然只是使用jQuery的阿贾克斯这样你就可以覆盖ajaxSend并使用标头一起发送的信息。
$(document).ajaxSend(function(e, xhr, options)
{
xhr.setRequestHeader("username", window.app.settings.credentials.username);
xhr.setRequestHeader("api_key", window.app.settings.credentials.api_key);
});
使用Ajax选项
如果您需要发送的只是一个或两个位置的信息,记住destroy
, fetch
, update
和save
方法只是快捷方式AJAX调用者。 所以,你可以添加所有的jQuery AJAX的参数 ,以这些方法为这样的:
// Remove the goal update view from the DOM
removeItem: function ()
{
this.model.destroy({
wait: true,
success: function ()
{
console.log("success");
},
error: function ()
{
console.log("error");
},
data:
{
username: window.app.settings.credentials.username,
api_key: window.app.settings.credentials.api_key
}
});
}
重写jQuery的AJAX方法
根据您的需求,这可能是更好的实现(注意,这是没有生产代码,您可能需要修改这个以满足您的需求,并使用它之前测试这个)
(function ($) {
var _ajax = $.ajax;
$.extend(
{
ajax: function (options)
{
var data = options.data || {};
data = _.defaults(data, {
username: window.app.settings.credentials.username,
api_key: window.app.settings.credentials.api_key
});
options.data = data;
return _ajax.call(this, options);
}
});
})(jQuery);
就为了这个职位的未来的读者,当你做一个model.destroy()不能传递任何数据,因为删除请求没有一个身体,看到这个问题的更多信息: https://github.com/ documentcloud /骨干网/问题/ 789
文章来源: How to override Backbone.sync so it adds the apikey and username at the end?