【发布时间】:2014-04-17 14:37:24
【问题描述】:
我正在使用以下 ajax:
$.ajax({
type: 'POST',
url: '/search/search.php',
crossDomain: true,
data: {data: data},
dataType: 'json',
async: false,
success: function (response){
if (response.success)
{
$('#search-results').show();
for(field in response.data){
error = response.field_errors[field];
var name = field.name;
var barcode = field.barcode;
var serial = field.serial;
$("#searchname").html(name);
$("#searchbarcode").html(barcode);
$("#searchserial").html(serial);
}
}
else {
console.log("fail");
}
},
});
我正在尝试遍历从 php 返回的行,并将每一行作为一行放在我的 html 表中。我从 php 得到正确的响应,但我的循环没有显示任何内容的HTML。
HTML 表格
<table class="table" id="search-results" style="display:none;">
<thead>
<tr>
<th>#</th>
<th>Name</th>
<th>Serial</th>
<th>Barcode</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td id="searchname"></td>
<td id="searchbarcode"></td>
<td id="searchserial"></td>
</tr>
</tbody>
</table>
PHP
$json = array();
if($num > 0)
{
$json['success'] = TRUE;
$i = 0;
while ($row = mysql_fetch_array($sql))
{
$json[$i]['data']['name'] = $row['name'];
$json[$i]['data']['barcode'] = $row['barcode'];
$json[$i]['data']['serial'] = $row['serial'];
$i++;
}
}
else
{
$json['success'] = FALSE;
}
echo json_encode($json);
【问题讨论】:
-
怎么了?你期望它做什么?它做了什么?请提出一个真正的问题。
-
我正在尝试为 php 响应中的每一行在我的 html 表中添加一行。它目前没有在 html 上显示任何内容,但给了我来自 php 的正确 json 响应
-
为什么要使用循环?由于 ID 是唯一的,因此您只会用每一行覆盖您的值。
console.log(field);在循环中为您提供了什么? -
我不想覆盖我的值,我已经用我的表格代码更新了我的问题。有没有办法为每一行生成html?
-
另外
var name = field.name;infor..in没有意义。你可能需要var name = response.data[field].name;。barcode和serial也是如此。
标签: javascript php ajax loops