jQuery requests php through ajax to traverse the json array to the code of recommendation in table

  • 2021-06-28 10:08:08
  • OfStack

html code (test.html), js at the bottom of html

The code is as follows:


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test-jquery-ajax-list</title>
</head>
<body>
<div class="main">
<table>
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>sex</th>
<th>time </th>
</tr>
</thead>
<tbody id="infolist">
</tbody>
</table>
</div>
</body>
<script src="http://apps.bdimg.com/libs/jquery/1.11.1/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
getList();
function getList(){
// jquery ajax  request 
$.ajax({
type:'post', // Request mode, default get
url :"http://localhost/ajax-demo-list/test.php",
data:{
getFunction:1
},success:function(data,status){
$('#infolist').html('');
$str = '';
$.each(data.list,function(i,val){
$str = $str + '<tr>';
$str = $str + '<td> '+val.id+' </td>';
$str = $str + '<td> '+val.name+' </td>';
$str = $str + '<td> '+val.sex+' </td>';
$str = $str + '<td> '+val.time+' </td>';
$str = $str + '</tr>';
});
$('#infolist').append($str);
if(data.list == "" || data.list.length < 0 || data.list == "undefined"){
$('#infolist').html('<td colspan="10" style="height:200px;text-align:center;color: #23527c"> No data available yet ...</td>');
}
},error:function(data,statsu){
alert(" Send request failed! ");
}
});
}
});
</script>
</html>

php Code (test.php)


<?php
header("Content-Type: application/json;charset=utf-8");
if($_REQUEST['getFunction']){
getList();
}
function getList(){
$data = array(
array(
'id' => 1,
'name' => 'xiaoming',
'sex' => ' male ',
'time' => '2016 year 1 month 22 day  14:45:46'
),
array(
'id' => 2,
'name' => ' Lao Zhang ',
'sex' => ' male ',
'time' => '2016 year 1 month 22 day  14:45:46'
),
array(
'id' => 3,
'name' => ' Rescue King ',
'sex' => ' male ',
'time' => '2016 year 1 month 22 day  14:45:46'
)
);
$list = json_encode(array('list'=>$data));
print_r($list);
// print_r(json_encode(array('list'=>$data=array())));
}

Related articles: