将JSON值附加到搜索结果div

时间:2017-03-29 18:49:18

标签: jquery json

我正在尝试将搜索查询的结果附加到div,但获得[object Object]结果。如何解析此json对象并从结果中仅检索/显示titlepermalink

json请求

$("#searchterm").keyup(function(e) {
 var q = $("#searchterm").val();
 //Only begin search with at least 3 characters.
 if(q.length > 3){
    ajax_search();
 }
 //Send search query
 function ajax_search(){
 $.getJSON("http://url-to-search?q=" + q, {
          dataType:'jsonp'
   },
 //Get results and make 'em look good
 function(data) {
   console.log(data);
   $("#results").empty();
   $("#results").append("Results for <b> " + q + "</b>");
     $.each(data.query.search, function(i, data) {
         $("#results").append(data);
     });
  });
 }
});

示例json

{
    "count": 50,
    "data": [{
        "id": "/folder/bob-jones/",
        "image": "https://image-url.jpg",
        "permalink": "/folder/bob-jones/",
        "text": "lots of text description here",
        "title": "Bob Jones",
        "type": "Employee"
    }]
}

2 个答案:

答案 0 :(得分:0)

编辑:

由于我没有您的网址来测试,这只是一个占位符示例:

$("#searchterm").keyup(function(e) {
 var q = $("#searchterm").val();
 //Only begin search with at least 3 characters.
 if(q.length > 3){
    ajax_search();
 }
 //Send search query
 function ajax_search(){
 $.getJSON("http://url-to-search?q=" + q, {
          dataType:'jsonp'
   },
 //Get results and make 'em look good
 function(data) {
   console.log(data);
   $("#results").empty();
   $("#results").append("Results for <b> " + q + "</b>");
     $.each(data.query.search, function(i, data) {
           alert(data.data[i].title);
     });
  });
 }
});

无论如何,与最初发布的概念相同。

https://jsfiddle.net/2kcdhbmy/2/

刚刚为你创建了一个JSFiddle:

var data = {
    "count": 50,
    "data": [{
        "id": "/folder/bob-jones/",
        "image": "https://image-url.jpg",
        "permalink": "/folder/bob-jones/",
        "text": "lots of text description here",
        "title": "Bob Jones",
        "type": "Employee"
    }]
}

alert(data.data[0].title);

https://jsfiddle.net/2kcdhbmy/

答案 1 :(得分:0)

data.query.search, 我认为它应该是data.data和内部函数data.title有些人认为...... $.each(data.data, function(i, data) { $("#results").append(data.title+" "+data.permalink); });