[英]how to pass an id containing / in backbone.js
HI my basic model which fetches data from server is working perfect. 嗨,我从服务器获取数据的基本模型运行良好。 I want to implement a search feature.
我想实现搜索功能。 When user enters any data the request goes to browser and desired model is returned.
当用户输入任何数据时,请求将转到浏览器并返回所需的模型。
var Book = Backbone.Model.extend({
urlRoot: '/books'
});
render: function(options) {
books = new Book({id:options.name});
books.fetch();
}
where 哪里
name = "search/"+dynamic_data;
Request URL that is being formed when i pass --> 'life' in variable dynamic_data 当我在变量dynamic_data中传递->'life'时形成的请求URL
http://host/path/search%2Flife
Request URL that i want 请求我想要的URL
http://host/path/search/life
How can I encode/escape my string to achieve the desired result. 我如何编码/转义我的字符串以获得所需的结果。 I have tried escape(), encodeURI(), encodeURIComponents
我已经尝试过escape(),encodeURI(),encodeURIComponents
According to your additionnal precisions stating that life is actually a book name... 根据您的其他精确度,指出生命实际上是一本书的名字。
It looks like Backbone is better integrated with RESTful API's. 看起来Backbone与RESTful API更好地集成了。 In REST, your urls should not contain verbs and to search books, you would do a
GET /books/?name=life
. 在REST中,您的网址不应包含动词,要搜索书籍,您可以执行
GET /books/?name=life
。
In that case, you would only have to define a Backbone.Collection
like: 在这种情况下,您只需定义一个
Backbone.Collection
:
var BooksCollection = Backbone.Collection.extend({
model: Book,
url: '/books'
});
The to fetch books: 拿书:
var books = new BooksCollection();
books.fetch({data : {name: 'life'}}); //GET /books/?name=life
If you really want your search operation to target /search/:name
, you will have to check the Backbone.Collection api, but I think you will want to look at http://backbonejs.org/#Sync 如果您确实希望搜索操作以
/search/:name
为目标,则必须检查Backbone.Collection api,但我认为您希望查看http://backbonejs.org/#Sync
You could override your collection's sync
method to something like: 您可以将集合的
sync
方法重写为类似以下内容:
Backbone.Collection.extend({
...
sync: function (method, model, options) {
//for read operations, call the search url
if (method === 'read') {
options.url = '/search/' + options.data.name;
delete options.data.name;
}
//call the default sync implementation
return Backbone.Collection.prototype.sync.apply(this, arguments);
}
});
In this cased calling books.fetch({data : {name: 'life'}});
在这种情况下,调用
books.fetch({data : {name: 'life'}});
will result in GET /books/life
. 将导致
GET /books/life
。
这将工作:
books = new Book({id:options.name}, {url: options.name));
encodeURIComponent()会将http://host/path/search%2Flife
为http://host/path/search/life
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.