ajax.php代码:
<html>
<head>
<meta type="text/html" charset="utf8" />
<title>异步请求数据库cms user表中的数据</title>
<script src="jquery-3.2.1.js"></script>
</head>
<body>
<input type="text" value="15" name="username" />
<button id="main" >提交</button>
<div id="user">
</div>
<script>
/*
问题:能不能不用json_encode()把数组转成json的格式?
1 dataType
1》html
2》json
3》jsonp跨域请求
*/
$("#main").click(function(){
//document.getElementsByName('username')[0].value;
var username=$("input[name='username']").val();
$.ajax({
type : 'get', //get
data:{'username':username},
dataType:'json',
url:'user.php',
//async:true, 同步 异步
//timeout:5000, 时间的限制
/* beforeSend:function(xhr){
console.log(xhr)
console.log('发送前')
}, */
success:function (response,status, xhr) {
$("#user").html("<table border=1 width=800></table>");
for(var i in response){
var str="<tr><td>"+response[i].id+"</td><td>"+response[i].username+"</td></tr>";
$("table").append(str);
}
},
error:function(){
alert("wronngh");
}
/*error:function(xhr,textStatus){
console.log('错误')
console.log(xhr)
console.log(textStatus)
},*/
/* complete:function(){
console.log('结束')
}*/
});
})
</script>
</body>
</html>
user.php代码部分:
<?php
@mysql_connect('localhost','root','123');
mysql_select_db('cms');
mysql_set_charset("utf8");
$sql="select *from cms_user where id<".$_GET['username'];
$res=mysql_query($sql);
$rows=[];
while($row=mysql_fetch_assoc($res)){
$rows[]=$row;
}
echo json_encode($rows);