我想使用ajax用数据库中的数据填充html表。
使用PHP生成此数组:
[
{
"custom_id":"453",
"name":"test",
"barcode":"3234234",
"grupa":"Служебна група",
"quantity_type":"бр.",
"quantity_number":"1",
"obekt":"Служебен обект",
"price_delivery":"0.00",
"price_sale":"0.00"
},
{
"custom_id":"2",
"name":"asdasd",
"barcode":"","grupa":
"Служебна група",
"quantity_type":"бр.",
"quantity_number":"1",
"obekt":"Служебен обект",
"price_delivery":"0.00",
"price_sale":"0.00"
},
{
"custom_id":"4",
"name":"Тутракан",
"barcode":"",
"grupa":"Служебна група",
"quantity_type":"бр.",
"quantity_number":"1",
"obekt":"Служебен обект",
"price_delivery":"0.00",
"price_sale":"0.00"
}
]
这是JS:
function loadTable() {
$.ajax({
type: "POST",
dataType: "json",
url: "generate_json/get_items_2.php", //Relative or absolute path to response.php file
data: {action: "load"},
success: function (response) {
//i don't know what exactly to put here
}
});
return false;
}
我可能需要循环,但是如何访问数组的元素?
答案 0 :(得分:2)
在success
回调中,您必须像response
那样循环返回的数组,以构造行并将它们附加到表中,如:
var response = [{
"custom_id": "453",
"name": "test",
"barcode": "3234234",
"grupa": "Служебна група",
"quantity_type": "бр.",
"quantity_number": "1",
"obekt": "Служебен обект",
"price_delivery": "0.00",
"price_sale": "0.00"
}, {
"custom_id": "2",
"name": "asdasd",
"barcode": "",
"grupa": "Служебна група",
"quantity_type": "бр.",
"quantity_number": "1",
"obekt": "Служебен обект",
"price_delivery": "0.00",
"price_sale": "0.00"
}, {
"custom_id": "4",
"name": "Тутракан",
"barcode": "",
"grupa": "Служебна група",
"quantity_type": "бр.",
"quantity_number": "1",
"obekt": "Служебен обект",
"price_delivery": "0.00",
"price_sale": "0.00"
}];
$.each(response, function(index, obj) {
var row = $('<tr>');
row.append('<td>' + obj.custom_id + '</td>');
row.append('<td>' + obj.name + '</td>');
row.append('<td>' + obj.barcode + '</td>');
row.append('<td>' + obj.grupa + '</td>');
$('table').append(row)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table border=1>
<tr>
<td>Custom id</td>
<td>Name</td>
<td>Barcode</td>
<td>Grupa</td>
</tr>
</table>