我正在使用 backbone-tastypie,但我很难让它正常工作。在 Tastypie 中,我为我的资源使用 ApiKeyAuthentication,因此每个 ajax 请求,我都需要将 apikey 和用户名附加到请求的末尾,或者发送添加在用户名和 api key 上的额外 header 。
我正在尝试使用主干删除一个 View 及其模型,代码如下:
// 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");
}});
},
函数执行后,浏览器尝试对以下 URL 执行 GET 请求:
:8000/api/v1/update/2/
它不包括 api_key 或末尾的用户名,并且在 url 末尾有一个尾部斜杠。我认为它正在尝试使用 Backbone.oldSync 来执行 GET 请求。我将如何做到这一点,以便同步在末尾包含用户名/api key 并删除尾部斜线?
在所有其他请求中,我通过将以下代码添加到 backbone-tastypie 来将 api key 和用户名附加到 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,
});
}
最佳答案
让我们探索可能性
使用 header
Backbone.sync 仍然只使用 jQuery ajax,因此您可以覆盖 ajaxSend 并使用 header 来发送信息。
$(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 调用者的快捷方式。所以你可以添加 all jQuery ajax parameters这些方法本身:
// 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);
关于javascript - 如何覆盖 Backbone.sync 以便它在末尾添加 apikey 和用户名?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10547498/