您的位置:首页 > 理论基础 > 计算机网络

《Java从入门到放弃》JSP入门篇:XMLHttpRequest的基本用法

2017-07-25 17:15 856 查看
不闲扯,直接开讲。
使用XMLHttpRequest对象,主要分为以下七个步骤:
创建对象

设置过期时间

设置数据格式

初始化 HTTP 请求

设置HTTP头请求

回传数据的处理

发送 HTTP 请求

对应代码如下所示
<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页面代码如下:
<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文件代码如下:

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();
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  AJAX XMLHttpRequest