-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjs_achieve_ajax.html
More file actions
62 lines (55 loc) · 1.94 KB
/
js_achieve_ajax.html
File metadata and controls
62 lines (55 loc) · 1.94 KB
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
61
62
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>js实现ajax</title>
<script>
//定义方法
function fun() {
//发送异步请求
//1.创建核心对象
var xmlhttp;
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else
{
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
//2. 建立连接
/*
参数:
1. 请求方式:GET、POST
* get方式,请求参数在URL后边拼接。send方法为空参
* post方式,请求参数在send方法中定义
2. 请求的URL:
3. 同步或异步请求:true(异步)或 false(同步)
*/
xmlhttp.open("GET","../ajax_servlet?username=cpu",true);
//3.发送请求
xmlhttp.send();
//4.接受并处理来自服务器的响应结果
//获取方式 :xmlhttp.responseText
//什么时候获取?当服务器响应成功后再获取
//当xmlhttp对象的就绪状态改变时,触发事件 onreadystatechange。
xmlhttp.onreadystatechange = function()
{
//判断readyState就绪状态是否为4,判断status响应状态码是否为200
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
//获取服务器的响应结果
var responseText = xmlhttp.responseText;
alert("responseText = " + responseText);
}
}
}
</script>
</head>
<body>
<input type="button" value="发送异步请求" onclick="fun();">
<input>
</body>
</html>