《Java从入门到放弃》入门篇:XMLHttpRequest的基本用法
不闲扯,直接开讲。
使用XMLHttpRequest对象,主要分为以下七个步骤:
-
创建对象
-
设置过期时间
-
设置数据格式
-
初始化 HTTP 请求
-
设置HTTP头请求
-
回传数据的处理
-
发送 HTTP 请求
对应代码如下所示
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
|
<script type= "text/javascript" > var xhr; function goAjax() { //1.创建对象 xhr = new XMLHttpRequest(); if (window.XMLHttpRequest) { xhr = new XMLHttpRequest(); } else if (window.ActiveXObject) { xhr = new ActiveXObject( "Microsoft.XMLHTTP" ); } //2.设置过期时间 xhr.setTimeout = 3000; //3.设置数据格式 xhr.responseType = "text" ; //4.初始化 HTTP 请求参数(未发送) xhr.open( "POST" , "servlet/AjaxLoginServlet" , true ); //5.设置HTTP请求 xhr.setRequestHeader( "Content-type" , "application/x-www-form-urlencoded" ); //6.回传数据的处理 //注册相关事件回调处理函数 //6.1 回传的数据加载完毕后执行 xhr.onload = function (e) { //alert(this.readyState + "||" + this.status); if ( this .readyState == 4 || this .status == 200) { var div = document.getElementById( "divContent" ); div.innerHTML = this .responseText; } }; //6.2访问出错 xhr.onerror = function (e) { alert( "登录失败!" ); }; //6.3超时 // xhr.ontimeout = function(e) { // }; //6.4状态改变 /* xhr.onreadystatechange = function(e){ if(this.readyState == 4 || this.status == 200) { alert(this.responseText); } } */ //7.发送数据 var username = document.getElementById( "username" ).value; var pwd = document.getElementById( "password" ).value; xhr.send( "username=" + username + "&password=" + pwd); } </script> |
HTML页面代码如下:
1
2
3
4
5
6
|
< body > 账号:< input type = "text" name = "username" id = "username" />< br /> 密码:< input type = "password" name = "password" id = "password" />< br /> < input type = "button" value = "登录" onclick = "goAjax();" /> < div id = "divContent" style = "width:200px; height: 100px;" ></ div > </ body > |
servlet文件代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //设置内容格式 response.setContentType( "text/html" ); PrintWriter out = response.getWriter(); //获取url中的用户名和密码 String username = request.getParameter( "username" ); String password = request.getParameter( "password" ); //成功输出success 失败输出fail if ( "haha" .equals(username) && "123" .equals(password)) { out.println( "success" ); } else { out.println( "fail" ); } out.flush(); out.close(); }
|
不努力一把,你怎么知道自己有多么废呢,啊哈哈哈哈!