《Java从入门到放弃》JSP入门篇:XMLHttpRequest的基本用法
2017-07-25 17:15
856 查看
不闲扯,直接开讲。
使用XMLHttpRequest对象,主要分为以下七个步骤:
创建对象
设置过期时间
设置数据格式
初始化 HTTP 请求
设置HTTP头请求
回传数据的处理
发送 HTTP 请求
对应代码如下所示
使用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(); }
相关文章推荐
- 《Java从入门到放弃》入门篇:XMLHttpRequest的基本用法
- XMLHttpRequest的基本用法
- 《Java从入门到放弃》框架入门篇:hibernate基本用法
- mui初级入门教程(三)— html5+ XMLHttpRequest 与mui ajax用法详解
- 《Java从入门到放弃》入门篇:springMVC基本用法
- 《Java从入门到放弃》入门篇:hibernate基本用法
- XMLHttpRequest 基本用法
- jsonp和XMLHttpRequest用法异同,jsp+js+servlet+mysql
- 《Java从入门到放弃》框架入门篇:springMVC基本用法
- JSP中使用XMLHttpRequest动态无刷新及其中文乱码处理
- XMLHttpRequest对象发送请求的基本步骤
- Hi there,Error:The absolute uri: http://java.sun.com/jsp/jstl/sql cannot be resolved in either web.xml or the jar files deployed
- XMLHttpRequest 的基本实例Ajax的应用
- ajax 入门基础之 XMLHttpRequest对象总结
- sharepoint form认证下跨域访问其他基本认证的系统(客户端用js的xmlhttprequest)的方法
- jQuery入门学习一:原始XMLHttpRequest方法回顾
- Ajax入门——XMLHttpRequest对象的使用
- 在java中"模拟" XMLHttpRequest
- XMLHTTPRequest简介以及用法加个人真实示例
- ajax 入门基础之--XMLHttpRequest对象总结(整理转)