保存到变量时如何只获取json对象的文本?

时间:2017-03-30 18:46:24

标签: javascript jquery json

我使用以下内容检索谷歌的结果表明工作正常:

function myGoogle() {
  var termS;          
  termS = $("#usp-title").val();
  var myKey = 'MY_KE';
  $.getJSON("https://www.googleapis.com/customsearch/v1", {
    q: termS,
    alt: "json",
    cx: "MY_CX",
    key: myKey,
    num: 10,
    hl: "it",
    siteSearch: "https://it.wikipedia.org/",
    language: "it",
    filter: "1",
    safe: "high"
  },
  function (data) {
    $.each(data.items, function(i, item) {
      var uniq = uniqueId('thing_');
      var $items = $($('<h3>"' + item.title + '"</h3>'));
      console.log($items);
    });
  });
}

控制台输出所有对象,而我只希望看到实际的标题文本

1 个答案:

答案 0 :(得分:2)

怎么样?

$items.forEach(function(item) {
  console.log(item.title);
});

*我假设你得到的数据与此类似 https://developers.google.com/custom-search/json-api/v1/reference/cse/list#response

“items”是一个数组,因此您可以通过array.forEach

遍历数组