ajax.php代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
<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代码部分:

1
2
3
4
5
6
7
8
9
10
11
12
<?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);

本文早期发布于个人 CSDN 博客:查看原文

站内搜索

没有找到内容!