我怎样才能将apiKey = 12341234附加到每个ajax请求上进行获取,创建,保存等等...... MongoLabs api需要这个,而且我一直在努力让它完全运行。
我目前正在使用骨干教程截屏,作者正在使用php框架为骨干应用程序创建api。我以为我会通过使用MongoLabs免费休息api来变得聪明......然后我烧了2天阅读文档并尝试使其工作。
我最接近的是在调用fetch时传递参数(不适用于create):Fetch Backbone collection with search parameters
{ data: $.param({'apiKey':'50b28f80e4b0995a3f4312a0'}) }
jsfiddle上的代码: http://jsfiddle.net/py4Pv/
# Encapsulate classes
window.App =
apiKey: { data: $.param({'apiKey':'50b28f80e4b0995a3f4312a0'}) }
Models: {}
Views: {}
Collections: {}
# The model for a single task
class App.Models.Task extends Backbone.Model
#override backbones 'id' attr to match mongo's '_id' attr
idAttribute: "_id"
defaults:
title: "None provided"
completed: 0
# The model for a collection of tasks
class App.Collections.Tasks extends Backbone.Collection
model: App.Models.Task
url: 'https://api.mongolab.com/api/1/databases/bbone_rest/collections/tasks/'
##################### Views, prob not important ########################
# View for a list of tasks
class App.Views.Tasks extends Backbone.View
tagName: 'ul'
initialize : () ->
@collection.on 'add', @addOne
render: ->
# Cycle through each task in collection and call @addOne
@collection.each @addOne
return this
addOne: (task) =>
task = new App.Views.Task({ model: task })
@$el.append( task.render().el )
# View for a single task unit
class App.Views.Task extends Backbone.View
tagName: 'li'
render: ->
@$el.html( this.model.get('title'))
return this
*编辑* 添加:$ .ajaxSetup({data:{key:“value”}在task.destroy()之后的标题信息
Request URL:https://api.mongolab.com/api/1/databases/bbone_rest/collections/tasks/1
Request Method:OPTIONS
Status Code:400 Bad Request
Request Headersview source
Accept:*/*
Accept-Charset:ISO-8859-1,utf-8;q=0.7,*;q=0.3
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8
Access-Control-Request-Headers:origin, accept
Access-Control-Request-Method:DELETE
Connection:keep-alive
Host:api.mongolab.com
Origin:null
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11
Response Headersview source
Connection:close
Content-Length:50
Content-Type:application/json;charset=utf-8
Date:Fri, 30 Nov 2012 06:42:57 GMT
Server:Apache/2.2.22 (Ubuntu)
答案 0 :(得分:2)
You can specify a function for the url
property of the model/collection - 这样你每次都应该能够在查询字符串中附加api。就是这样的(对不起,我不确定Mootools的语法):
url: () =>
return 'https://api.mongolab.com/api/1/databases/bbone_rest/collections/tasks/' + this._id + '?api=' + App.apiKey
答案 1 :(得分:0)
你试过了吗?
$.ajaxSetup({
data: {
key: "value"
}
这将为每个ajax请求添加密钥参数。在ajaxSetup中声明的数据是累积的。
答案 2 :(得分:0)
处理此问题的最佳方法是 ajaxPrefilter
var api_key = '465456132456'
$.ajaxPrefilter( function( options, originalOptions, jqXHR ) {
options.url = 'YOUR_URL' + options.url + '?key=' + api_key;
});