在ajax调用中,我成功收到一个json数组。 在ajax success函数中,我想用HTML显示这个数组。 我可以一次显示整个数组,但我想循环 数组的长度并逐个显示元素。 见下面的代码
$.ajax({
type: "POST",
: "json",
url: "response.php",
data: data,
success: function(data) {
$(".airports").html(
"<button type='button' class='btn btn-info btn-block' data-toggle='collapse' data-target='#ap'>Airports</button>" +
"<div id='ap' class='collapse'>" +
"<b>Departure airports</b><br>" + data["deptAirports"].length + "<br>" +
for (i = 0; i < data["deptAirports"].length; i++){
data["deptAirports"][i] + "<br>" +
}
"<b>Destination airports</b><br>" + data["destAirports"] +
"</div>"
)
destAirports数组只是在HTML中抛出,这是有效的。然而,上面的for循环打破了一切,它不会工作。
我遗失了什么?
答案 0 :(得分:1)
您不能将字符串与循环连接....将代码更改为:
$.ajax({
type: "POST",
url: "response.php",
data: data,
success: function(data) {
var html = "<button type='button' class='btn btn-info btn-block' data-toggle='collapse' data-target='#ap'>Airports</button>" +
"<div id='ap' class='collapse'>" + "<b>Departure airports</b><br>" + data["deptAirports"].length + "<br>";
for (i = 0; i < data["deptAirports"].length; i++){
html += data["deptAirports"][i] + "<br>";
}
html += "<b>Destination airports</b><br>" + data["destAirports"] + "</div>";
$(".airports").html(html);
答案 1 :(得分:1)
您的语法(和表单)不正确。 for循环不能只放在字符串连接中。 for循环不会生成内联文本值。相反,您需要一些从数组中生成内联文本值的东西。一种选择是使用Array.join()
。以下是您可以在JavaScript控制台中运行的示例:
var someArray = [];
someArray.push('Value 1');
someArray.push('Value 2');
someArray.push('Value 3');
var myText = "<span>" + someArray.join("<br />") + "</span>";
console.debug(myText);
输出:
<span>Value 1<br />Value 2<br />Value 3</span>
将它放入OP的代码中,我们发现如下:
$.ajax({
type: "POST",
: "json",
url: "response.php",
data: data,
success: function(data) {
$(".airports").html(
"<button type='button' class='btn btn-info btn-block' data-toggle='collapse' data-target='#ap'>Airports</button>" +
"<div id='ap' class='collapse'>" +
"<b>Departure airports</b><br>" +
data["deptAirports"].length + "<br>" +
data["deptAirports"].join("<br />") + "<br>" +
"<b>Destination airports</b><br>" + data["destAirports"] +
"</div>");
}
});
答案 2 :(得分:0)
试试这个
$.ajax({
type: "POST",
dataType : "json",
url: "response.php",
data: data,
success: function(data) {
var markup = "<button type='button' class='btn btn-info btn-block' data-toggle='collapse' data-target='#ap'>Airports</button>";
markup += "<div id='ap' class='collapse'>";
markup += "<b>Departure airports</b><br>";
markup += data["deptAirports"].length + "<br>";
$.each( data["deptAirports"] , function(index,value){
markup += value + "<br>";
});
markup += "<b>Destination airports</b><br>" + data["destAirports"] + "</div>";
$(".airports").html(markup);
}
});