无法使用jquery

时间:2019-07-03 14:47:27

标签: jquery json

我要将从服务器收到的搜索结果转换为无序列表:

function searchSuccess(json, textStatus, jqXHR) {
  console.log('json is:', json);
  var html= "<ul>";
  Object.keys(json).forEach(function(key, val) { 
    html += "<li><a href=\'" + val['slug'] + "\'>" + val['title'] +"</a></li>";    
  });
  html +="</ul>"
  $('#search-results').append(html);
}

我在控制台中看到的json是:

json is: [{"title":"Hello World","slug":"hello-world"},{"title":"I'm a title","slug":"I-am-title"}]

但是,呈现的是li列表,而不是链接的undefined

这是怎么了?我该如何解决?

2 个答案:

答案 0 :(得分:2)

您在json中有一个带有javascript对象的数组列表。这些代码有效:

  • 您的代码几乎没有调整:

var json = '[{"title":"Hello World","slug":"hello-world"},{"title":"I\'m a title","slug":"I-am-title"}]';

function searchSuccess(json) {
  console.log('json is:', json);
  var html= "<ul>";
  jsonObject = JSON.parse(json);
  
  jsonObject.forEach(function(searchresult) { 
    html += "<li><a href=\'" + searchresult.slug + "\'>" + searchresult.title +"</a></li>";    
  });
  html +="</ul>"
  $('#search-results').empty().append(html);
}

searchSuccess(json);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="search-results"></div>

  • Nicer jQuery方式:

var json = '[{"title":"Hello World","slug":"hello-world"},{"title":"I\'m a title","slug":"I-am-title"}]';

function searchSuccess(json) {
  var $ul = $('<ul>');
  jsonObject = JSON.parse(json);
  
  jsonObject.forEach(function(searchresult) {
    var $li = $('<li>');
    var $a = $('<a>');
    $a.attr('href', searchresult.slug)
    $a.text(searchresult.title);
    $li.append($a);
    $ul.append($li);
  });
  $('#search-results').empty().append($ul);
}

searchSuccess(json);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="search-results"></div>

答案 1 :(得分:0)

您可以使用for循环并像这样遍历json对象(基于您指定为对象而不是字符串的json):

var sample1 = new DateTime(2013, 1, 1);
var sample2 = new DateTime(1913, 1, 1);

您可以将json指定为对象,也可以将其从字符串解析为对象,如下所示:

var json = [{"title":"Hello World","slug":"hello-world"},{"title":"I\'m a title","slug":"I-am-title"}];

for (var key in json) {
  console.log(json[key]);
  console.log(json[key]['slug']);
  console.log(json[key]['title']);
}