请查看 Fiddle Example
谁能告诉我,为什么即使 Ajax 请求已成功完成,div 元素 #tablearea
中仍会附加“未定义”文本?
JSON:
[{"title":"A","nation":"Germany,Japan","city":"Hamburg,Toyko","Name":"John,Peter,Tom"},{"title":"B","nation":"Japan,Italy","city":"Toyko","Name":"Adam,Tom"},{"title":"C","nation":"Germany","city":"Berlin,Hamburg","Name":"Mary,Tom"}]
jQuery:
$.ajax({
url: "https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%20%3D%22http%3A%2F%2Fgoo.gl%2FRgDyl4%22&format=json&diagnostics=true&callback=",
success: function (data) {
var item_html;
item_html += "<table><thead><tr><th></th>";
$(data.query.results.json.json).each(function (index, item) {
var title = item.title;
item_html += '<th>'+title+'</th>';
});
item_html += "</tr></thead><tbody><tr><td>Germany</td>";
$(data.query.results.json.json).each(function (index, item) {
var nations = item.nation.replace(/ /g,'').split(",");
console.log(nations);
if ($.inArray('Germany', nations) < 0)
{
item_html += "<td>No</td>";
}else{
item_html += "<td>Yes</td>";
}
});
item_html += "</tr><td>Berlin</td>";
$(data.query.results.json.json).each(function (index, item) {
var citys = item.city.replace(/ /g,'').split(",");
if ($.inArray('Berlin', citys) < 0)
{
item_html += "<td>No</td>";
}else
{
item_html += "<td>Yes</td>";
}
});
item_html += "</tr><td>Peter</td>";
$(data.query.results.json.json).each(function (index, item) {
var names = item.Name.replace(/ /g,'').split(",");
if ($.inArray('Peter', names) < 0)
{
item_html += "<td>No</td>";
}else
{
item_html += "<td>Yes</td>";
}
});
item_html += "</tr></tbody></table>";
$('#tablearea').append(item_html);
}
});
HTML:
<div id="tablearea"></div>
返回结果:
<div id="tablearea">
undefined
<table>
<thead>
<tr>
<th></th>
<th>A</th>
<th>B</th>
<th>C</th>
</tr>
</thead>
<tbody>
<tr>
<td>Germany</td>
<td>Yes</td>
<td>No</td>
<td>Yes</td>
</tr>
<tr>
<td>Berlin</td>
<td>No</td>
<td>No</td>
<td>Yes</td>
</tr>
<tr>
<td>Peter</td>
<td>Yes</td>
<td>No</td>
<td>No</td>
</tr>
</tbody>
</table>
</div>
最佳答案
您必须首先使用 ""
初始化 item_html
,如下所示:
item_html = "";
如果你只是声明item_html
而不初始化它,它是未定义的。向其附加字符串会导致代码的行为..
看到这个fiddle以获得进一步的解释。
关于javascript - Ajax调用成功,但有一个未定义的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24278159/