我们需要发送请求
https://api.github.com/search/repositories?q=angular+user:angular&order=desc
但在控制台请求中
https://api.github.com/search/repositories?q=angular%2Buser%3Aangular&order=desc
集合
var RepoCollection = Backbone.Collection.extend({
url: 'https://api.github.com/search/repositories',
initialize: function () {},
fetch: function(options) {
var params = {
q:"angular+user:angular",
order:"desc"
};
return Backbone.Collection.prototype.fetch.call(this, {
data: $.param(params)
});
}
});
例如:
请求:https://api.github.com/search/repositories?q=com%2Buser%3Attomashuk&order=desc
{
"total_count": 0,
"incomplete_results": false,
"items": [
]
}
请求:https://api.github.com/search/repositories?q=com+user:ttomashuk&order=desc
{
"total_count": 1,
"incomplete_results": false,
"items": [
{
"id": 104921385,
"name": "CompanyOrganizer",
"full_name": "ttomashuk/CompanyOrganizer",
.........
"score": 1.2680688
}
]
}
答案 0 :(得分:3)
jQuery documentation on $.param
显示您正在寻找的内容:
var myObject = {
a: {
one: 1,
two: 2,
three: 3
},
b: [1, 2, 3]
};
var recursiveEncoded = $.param(myObject);
var recursiveDecoded = decodeURIComponent($.param(myObject));
console.log("encoded:", recursiveEncoded);
console.log("decoded:", recursiveDecoded);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
应该输出:
encoded: a%5Bone%5D=1&a%5Btwo%5D=2&a%5Bthree%5D=3&b%5B%5D=1&b%5B%5D=2&b%5B%5D=3
decoded: a[one]=1&a[two]=2&a[three]=3&b[]=1&b[]=2&b[]=3
所以你可以用:
获取return Backbone.Collection.prototype.fetch.call(this, {
data: decodeURIComponent($.param(params))
});
你还应该传递最初传递的任何其他选项以获取到原来的提取调用,这样你的覆盖是透明的:
fetch: function(options) {
options = options || {};
// extend the passed data with the default
options.data = decodeURIComponent($.param(_.extend({
q: "angular+user:angular",
order: "desc"
}, options.data)));
return Backbone.Collection.prototype.fetch.call(this, options);
}