我正在尝试从api获取数据,并希望在div中显示每个json数组对象或放置2个换行符。我的代码只显示页面上的所有数组对象,但我希望将每个对象数据分开以获得良好的可读性。如何调整我的代码,以便在每个objs内容后都有换行符?
这是我的json:
{
"players": [
{
"name": "Marcos Alonso",
"position": "Left-Back",
},
{
"name": "Marco van Ginkel",
"position": "Central Midfield",
}
articles": [
{
"author": "Stephen Walter",
"url": "http://www.telegraph.co.uk/news/2017/04/15/disruptive-stag-party-revellers-thrown-plane-manchester-airport/",
},
{
"author": "TMG",
"url": "http://www.telegraph.co.uk/news/2017/04/15/north-korea-marks-anniversary-military-parade-pyongyang-pictures/",
}],
...........
......
}
我的jQuery看起来像这样:
$(function () {
$('#getstuff').click(function () {
var requestdata = $('#choi').val();
var result = $('#resultdiv');
$.ajax({
type: 'GET',
url: 'http://localhost/project/v1/api/webservice',
dataType: 'json',
success: function (data) {
var html = '';
var array = data[requestdata];
if (array) {
$.each(array, function (i) {
$.each(array[i], function (key, value) {
html += ('<li>' + key + ': ' + value + '</li>');
});
result.html(html);
});
}
}
});
});
});
如果我搜索&#34;玩家&#34;,我想要这样的东西。太空btw objs;
name : Marcos Alonso
Position: Left-Back
name : Marco van Ginkel
Position: Central Midfield
但是当我运行我的代码时,我就是那个:
name : Marcos Alonso
Position: Left-Back
name : Marco van Ginkel
Position: Central Midfield
我需要帮助,如何将每个objs内容换行,或将每个objs内容放在div中。哪个更好。提前谢谢..
答案 0 :(得分:0)
<br>
方式:
$(function () {
$('#getstuff').click(function () {
var requestdata = $('#choi').val();
var result = $('#resultdiv');
$.ajax({
type: 'GET',
url: 'http://localhost/project/v1/api/webservice',
dataType: 'json',
success: function (data) {
var html = '';
var array = data[requestdata];
if (array) {
$.each(array, function (i) {
$.each(array[i], function (key, value) {
html += ('<li>' + key + ': ' + value + '</li>');
});
html += '<br><br>'; // this is where to add it
result.html(html);
});
}
}
});
});
});
以<div>
方式,这将是首选(也因为它将列表项包装在列表元素中):
$(function () {
$('#getstuff').click(function () {
var requestdata = $('#choi').val();
var result = $('#resultdiv');
$.ajax({
type: 'GET',
url: 'http://localhost/project/v1/api/webservice',
dataType: 'json',
success: function (data) {
var html = '';
var array = data[requestdata];
if (array) {
$.each(array, function (i) {
html += '<div><ul>';
$.each(array[i], function (key, value) {
html += ('<li>' + key + ': ' + value + '</li>');
});
html += '</ul></div>';
result.html(html);
});
}
}
});
});
});