XMLHttpRequest的基本用法
来源:互联网 发布:刺客信条枭雄优化好 编辑:程序博客网 时间:2024/06/06 18:39
创建对象
设置过期时间
设置数据格式
初始化 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>
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();}
阅读全文
0 0
- XMLHttpRequest的基本用法
- XMLHTTPRequest 的用法
- XMLHttpRequest 的用法
- XMLHttpRequest的用法
- XMLHttpRequest的用法
- XMLHttpRequest对象的基本属性:
- XMLHttpRequest对象的基本使用
- XMLHttpRequest 及其open()的用法
- xmlHttpRequest 用法。
- Ajax XMLHttpRequest 用法
- XMLHttpRequest初级用法
- XMLHttpRequest用法介绍
- XMLHttpRequest用法详解
- AJAX--XMLHttpRequest用法介绍
- XMLHttpRequest用法介绍
- rpm的基本用法
- sfc的基本用法
- vi 的基本用法
- dfs-字符全排列
- APP的性能测试(二)
- Mysql 修改结束符号
- Android如何http获取数据库数据
- 浏览器常见兼容性问题
- XMLHttpRequest的基本用法
- 三体全集 mobi 下载
- APP的性能测试(三)
- Linux的小作业
- MPC5744——系统集成单元(SIUL2)
- 交集差集并集
- glusterfs分布式存储部署
- App中如何启动另一个App
- 'module' object is not callable