3

我正在使用骨干美味,但我很难让它正常工作。在 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");
  }});
},

函数执行后,浏览器尝试对以下 URL 执行 GET 请求:

:8000/api/v1/update/2/

它不包括末尾的 api_key 或用户名,并且在 url 的末尾有一个斜杠。我认为它正在尝试使用 Backbone.oldSync 来执行 GET 请求。我将如何做到这一点,以便同步在末尾包含用户名/api 键并删除尾部斜杠?

在所有其他请求中,我已经通过将以下代码添加到主干美味来将 api 密钥和用户名附加到 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,
    });
}
4

2 回答 2

17

让我们探索可能性

使用标题

Backbone.sync 仍然只使用 jQuery ajax,因此您可以覆盖 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、和方法只是 ajax 调用者的快捷方式。因此,您可以将所有 jQuery ajax 参数添加到这些方法中,如下所示:fetchupdatesave

// 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);
于 2012-05-11T09:19:10.350 回答
0

只是为了这篇文章的未来读者,当您执行 model.destroy() 时,您不能传递任何数据,因为删除请求没有正文,请参阅此问题以获取更多信息: https ://github.com/文档云/骨干网/问题/789

于 2012-10-26T04:10:23.500 回答