jQuery通过ajax请求php遍历json数组到table中的代码(推荐)
html代码(test.html),js在html底部
具体代码如下所示:
<!DOCTYPEhtml>
<htmllang="en">
<head>
<metacharset="UTF-8">
<title>test-jquery-ajax-list</title>
</head>
<body>
<divclass="main">
<table>
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>sex</th>
<th>time</th>
</tr>
</thead>
<tbodyid="infolist">
</tbody>
</table>
</div>
</body>
<scriptsrc="http://apps.bdimg.com/libs/jquery/1.11.1/jquery.js"></script>
<scripttype="text/javascript">
$(document).ready(function(){
getList();
functiongetList(){
//jqueryajax请求
$.ajax({
type:'post',//请求方式,默认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('<tdcolspan="10"style="height:200px;text-align:center;color:#23527c">暂无相关数据...</td>');
}
},error:function(data,statsu){
alert("发送请求失败!");
}
});
}
});
</script>
</html>
php代码(test.php)
<?php
header("Content-Type:application/json;charset=utf-8");
if($_REQUEST['getFunction']){
getList();
}
functiongetList(){
$data=array(
array(
'id'=>1,
'name'=>'xiaoming',
'sex'=>'男',
'time'=>'2016年1月22日14:45:46'
),
array(
'id'=>2,
'name'=>'老张',
'sex'=>'男',
'time'=>'2016年1月22日14:45:46'
),
array(
'id'=>3,
'name'=>'捞王',
'sex'=>'男',
'time'=>'2016年1月22日14:45:46'
)
);
$list=json_encode(array('list'=>$data));
print_r($list);
//print_r(json_encode(array('list'=>$data=array())));
}
以上所述是小编给大家介绍的jQuery通过ajax请求php遍历json数组到table中的代码(推荐),希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对毛票票网站的支持!