如何在不对 URL 参数进行编码的情况下获取 backbone 集合?

How to fetch a backbone collection without encoding the URL parameters?

我们需要发送请求

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
        }
      ]
    }

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 的任何其他 选项 传递给原始 fetch 调用,以便您的覆盖是透明的:

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);
}