在处理了一个带有ajax-jQuery的小型搜索引擎和PHP中的函数之后,我有一个数组JSON,我想要处理这个用于追加表中的行但是我感到困惑。
来自查询mysql的JSON格式没问题,但我不知道如何生成表或在我的存在表中追加过程数据。
我认为每个都采用JSON的每个元素,但我不能认为。
注意:我的JSON代码是以这种方式生成的
...........
$jsonSearchResults = array();
while ($row = mysql_fetch_assoc($result)) {
$jsonSearchResults[] = array(
'clavemat' => $row['cve_mat'],
'tipomat' => $row['tipo_mat'],
'titulomat' => $row['titulo_mat'],
'autormat' => $row['autor_mat'],
'editmat' => $row['edit_mat'],
'success' => 'success'
);
}
echo json_encode ($jsonSearchResults);
表格HTML
.........
<table class="busqueda">
<tr>
<th scope="col">Clave</th>
<th scope="col">Tipo</th>
<th scope="col">Título</th>
<th scope="col">Autor</th>
<th scope="col">Editorial</th>
</tr>
</table>
........
JSON代码
[
{
"clavemat":"LICOELMCUS",
"tipomat":"Libro",
"titulomat":"Contabilidad",
"autormat":"Elias Flores",
"editmat":"McGraw Hill",
"success":"success"
},
{
"clavemat":"LICUDEMCNU",
"tipomat":"Libro",
"titulomat":"Curso java",
"autormat":"Deitel",
"editmat":"McGraw Hill",
"success":"success"
},
{
"clavemat":"REECMUMUNU",
"tipomat":"Revista",
"titulomat":"Eclipses",
"autormat":"Muy Interesante",
"editmat":"Muy interesante",
"success":"success"
},
{
"clavemat":"TEPLPLTENU",
"tipomat":"Tesis",
"titulomat":"Platanito Show",
"autormat":"Platanito",
"editmat":"Telehit",
"success":"success"
}
]
AJAX.JQUERY FILE
$.ajax({
type: "POST",
url: action,
data: dataSearch,
success: function (response) {
if (response[0].success == "success") {
alert("Si hay datos");
} else {
alert("No hay datos");
}
}
});
return false;
});
答案 0 :(得分:2)
这应该有效
$.each(response, function (index, record) {
var row = $("<tr />");
$("<td />").text(record.clavemat).appendTo(row);
$("<td />").text(record.tipomat).appendTo(row);
$("<td />").text(record.titulomat).appendTo(row);
$("<td />").text(record.autormat).appendTo(row);
$("<td />").text(record.editmat).appendTo(row);
row.appendTo("table.busqueda");
});
上面的代码将行附加到具有类“busqueda”的现有表。
答案 1 :(得分:2)
在表格中,您可以添加<tbody>
元素作为动态行的容器:
<table class="busqueda">
<thead>
<tr>
<th scope="col">Clave</th>
<th scope="col">Tipo</th>
<th scope="col">Título</th>
<th scope="col">Autor</th>
<th scope="col">Editorial</th>
</tr>
</thead>
<tbody id="dynamic_rows">
<!-- Ajax results go here -->
</tbody>
</table>
然后在ajax成功回调中,您将呈现行:
if (response[0].success == "success") {
// Render dynamic rows here
var $dynamic_rows = $('#dynamic_rows');
// clear out old rows
dynamic_rows.html('');
///////
// You can use the row building code from Rafael's answer here
// except append to $dynamic_rows
} else {
alert("No hay datos");
}