如何使用$ .each迭代$ .JSON结果数组

时间:2013-11-16 01:52:11

标签: json each

我只收回数组中的第一个结果,并希望检索所有可用的结果。

    function runForm(){
        $("#stock_news").html("");
        var stockSymbol = $("input").val();

//very long str

 var newsStocks = "http://query.yahooapis.com/v1/public/yql?
    q=select%20*%20from%20html%20where%20url%3D'http%3A%2F%2Ffinance.yahoo.com
%2Fq%3Fs%3D"+stockSymbol+"'%20and%20xpath%3D'%2F%2Fdiv%5B%40id%3D%22yfi_headlines
     %22%5D%2Fdiv%5B2%5D%2Ful%2Fli%2Fa'&format=json&diagnostics=true&callback=";

//getJSON       

$.getJSON(newsStocks, function(data) {
  var headlines = data.query.results.a[0];
//newsStr

  newsStr = "<h3 style='text-decoration:underline'>Current Headlines</h3><p><ol>
<li><a href='"+headlines.href+"'>"+headlines.content+
    "</a></li></ol></p>";
    $("#stock_news").html(newsStr);
                });

1 个答案:

答案 0 :(得分:0)

您没有提供足够的信息,但我猜测这个var headlines = data.query.results.a[0];是您的问题。看起来其他结果似乎都存在,但是你将它们过滤掉了。 console.log(data)console.log(data.query.results)并查看其中的所有内容。否则,请使用更多信息更新您的问题。

<强>更新

这是一个非常基本的ajax调用(使用jQuery)和for loop循环并使用每个结果。

$.get('path/here', function(data) {
  //if your data is an array
  for (var i=0; i<data.length; ++i) {
    var item = data[i];
    console.log(item);
  }
});

Here's a live demo (click),但由于路径无效,我不打算使用ajax数据。

以下是相同的示例,但使用$.each。我更喜欢for loop ...为什么使用jQuery这么简单?

$.get('path/here', function(data) {
  $.each(data, function(item, index) {
    console.log(index);
  });
});
相关问题