2011-12-05 38 views
5

我试图检索雅虎自动完成。jQuery:雅虎自动完成/ Autosuggest

雅虎的JSON网址是:http://ff.search.yahoo.com/gossip?output=fxjson&command=query

所以我必须:

$("selector").autocomplete({ 
     source: function(request, response) { 
      $.ajax({ 
       url: "http://ff.search.yahoo.com/gossip", 
       dataType: "jsonp", 
       data: { 
        "output" : "fxjson", 
        "command" : request.term 
       }, 
       success: function(data) { 
        response(data[1]) 
       } 
      }) 
     } 
    }); 

而且这里有一个例子:http://jsfiddle.net/yQbdb/

可有人发现一个错误或我做错了什么?它应该工作。

感谢

+0

哇,看起来像一个错误。 – noob

回答

1

设置outputjsonp为我工作。

查看example query的输出结构。

解释如下。

代码是HERE

$("#wd6450").autocomplete({ 
    source: function(request, response) { 
     $.ajax({ 
      url: "http://ff.search.yahoo.com/gossip", 
      dataType: "jsonp", 
      data: { 
       "output": "jsonp", 
       "command": request.term 
      }, 
      success: function(data) { 
       var suggestions = []; 
       // for each element in the data.gossip.results array ... 
       $.each(data.gossip.results, function(i, val) { 
        // .. push the value of the key inside our array 
        suggestions.push(val.key); 
       }); 
       // call response with our collected values 
       response(suggestions); 

      } 
     }); 
    } 
}); 

说明:

通过使用dataType: "jsonp" jQuery的期望的输出格式是在JSONP。当您使用output: "fxjson"从您的代码拨打电话时,该URL看起来像this但您可以看到输出不是有效的JSONP,因为回调未被调用。

就当你指定output: "jsonp"查询看起来像this,正如你可以看到输出另一方面是有效JSONP - 回调被调用。

您在评论中链接了一个亚马逊例子。 $.ajax()那里的电话会尝试URL如this。来自亚马逊的web服务的输出是有效的JSONP,因为回调被所有的数据调用。

所以结果是:如果您通过配置$.ajax()output: "jsonp"在URL中提供?output=jsonp参数,雅虎web服务将返回JSONP格式。亚马逊的web服务默认返回这种格式,没有任何额外的参数。这是特定于Web服务的配置,必须咨询其文档或其他相关资源。

关于JSONP的信息可用HERE

+0

这是对的,但它对我没有意义。你能否把它分解给我,这样我可以在将来使用它?因为想象我正在使用ebay的autosuggest:http://anywhere.ebay.com/services/suggest/?q=test没有输出等。谢谢 – jQuerybeast

+0

@jQuerybeast将'output'设置为'fxjson'正在制作'$。 ajax'生气,因为JSONP回调没有被调用。我通过向ajax调用添加错误处理程序来找到它。然后我试图改变'output'并开始工作。 – kubetz

+0

JSONP正在从dataType中调用。如果你不得不将输出设置为jsonp,这是如何工作的:http://jsfiddle.net/HaQTA/? – jQuerybeast