2013-08-21 41 views
0

我不明白如何让Backbone.sync适合我的情况。 这就是为什么我仍然使用这种常用的Ajax请求我的项目:Backbone base64编码

$.ajax({ 
    url: request, 
    status: status, 
    type: 'GET', 
    dataType: 'json', 
    beforeSend: function (req) { req.setRequestHeader("Authorization", auth) }, 
    success: function (data, status) { 
      //update the model 
    }, 
    error: function(XMLHttpRequest, textStatus, errorThrown){ 
     //do stuff 
    } 
}); 

我需要一个base64编码授权添加到请求头和更新的模式。我从服务器获得的数据包含比我的模型需要更多的信息。这就是为什么我不能直接参考的模型像这样的网址:

var MyApp.myModel = Backbone.Model.extend({ 
url: '/someResourceUrl' 
}); 
MyApp.myModel.fetch(); 

我需要做某事。像:

var MyApp.myModel = Backbone.Model.extend({ 
    url: 'anyurl', 
    sync: myOwnSpecificSync, 
}); 
//Define the sync function: 
myOwnSpecificSync = function(method, model, options) { 
//add header 
//return only specific parameters of the success data 
}; 
//let the model fetch the data from the server 
MyApp.myModel.fetch(); 

但我不知道如何实现函数..或者如果它是正确的。

回答

1
var AuthSync = function(method, model, options) { 
    options.beforeSend = function() { 
    console.log('add auth header here'); 
    }; 
    return Backbone.sync(method, model, options); 
}; 

var Model = Backbone.Model.extend({ 
    url : 'http://fiddle.jshell.net/echo/json/', 
    sync : AuthSync 
}); 

new Model().fetch(); 
+0

THX为您ansear,我会尝试一下:) – marcel

+0

后我曾经使用过它和它的作品:)对不起,我没有解释,我认为的代码是清楚 –

+0

如果我设置beforeSend方法我在我的ajax请求中做了什么,它不工作... function(req){req.setRequestHeader(...);我必须使用某物吗?其他但setRequestHeader()? – marcel