在.getJson()中传递相同参数的多个值

时间:2014-06-19 10:31:25

标签: javascript jquery json api youtube

我正在尝试跟随:

<script>
  var topic_id = '/m/04136kj';
  var service_url = 'https://www.googleapis.com/freebase/v1/topic';
  var params = {
                filter: "/common/topic/article",
                filter:"/common/topic/notable_for",
                filter: "/common/topic/notable_types",
                filter: "/type/object/type"
               };

  $.getJSON(service_url + topic_id + '?callback=?', params, function(topic) {
    //do something with response.
  });
</script>

如果您发现我要为filter传递4个值。但是我从FIDDLER捕获的最终网址只包含最后一个值(/type/object/type),我只尝试了一个参数,它工作正常(任何参数),但没有多个值。我怎样才能形成正确的参数?

修改

在第一个回答中传递如下所示的数组会错误地对URL进行编码。它会在[]之后添加filter,即它在网址中传递filter[]=而不是filter=

var params = {
           filter: ["/common/topic/article", "/common/topic/notable_for",
                      "/common/topic/notable_types", "/type/object/type"]
           };

2 个答案:

答案 0 :(得分:1)

将过滤器对象创建为数组

var topic_id = '/m/04136kj';
var service_url = 'https://www.googleapis.com/freebase/v1/topic';
var params = {
    filter: ["/common/topic/article", "/common/topic/notable_for", "/common/topic/notable_types", "/type/object/type"]
};
//used to remove the the suffix [] in the array param
$.ajaxSetup({ traditional: true });
$.getJSON(service_url + topic_id + '?callback=?', params, function (topic) {
    //do something with response.
});

答案 1 :(得分:0)

需要创建param对象,就像它是一个HTML <form>对象一样,作为一系列名称/值对。

var topic_id = '/m/04136kj';
var service_url = 'https://www.googleapis.com/freebase/v1/topic';
var filter = ["/common/topic/article", "/common/topic/notable_for",
    "/common/topic/notable_types", "/type/object/type"];
var params = filter.map(function(f) { return { name: "filter", value: f }; });

$.getJSON(service_url + topic_id + '?callback=?', params, function (topic) {
    //do something with response.
});