码迷,mamicode.com
首页 > Web开发 > 详细

JS原生Ajax

时间:2018-11-16 22:27:25      阅读:238      评论:0      收藏:0      [点我收藏+]

标签:form   enc   new   char   ready   ati   其他   str   用户   

1、Ajax概述

异步访问:客户端发送请求到服务器,无论服务器是否返回响应,客户端都可以随意进行其他操作,不会被卡死。

Ajax运行原理:页面发出请求,会将请求发送给浏览器中内置的Ajax引擎,Ajax引擎会提交请求到服务器端,等待服务器响应期间,用户可以进行其他操作,直到服务器端将数据返回给Ajax引擎后,会出发设置的事件,执行自定义js的逻辑代码完成某种功能。

2、使用js原生Ajax的步骤

  1. 创建Ajax引擎对象
  2. 为Ajax引擎对象绑定监听
  3. 绑定提交地址
  4. 发送请求
  5. 接受相应数据
 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4 <meta charset="UTF-8">
 5 <title>Insert title here</title>
 6     <script type="text/javascript">
 7         function fn1() {
 8             //alert();
 9             // 1、创建ajax引擎对象(所有操作都通过ajax引擎对象完成)
10             var xmlHttp = new XMLHttpRequest();
11             // 2、为ajax引擎对象绑定监听(监听服务器是否响应)
12             xmlHttp.onreadystatechange = function() {
13                 //alert();
14                 // 5、接收响应数据
15                 if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
16                     var res = xmlHttp.responseText;
17                     document.getElementById("span1").innerHTML = res;
18                 }
19             }
20             // 3、绑定提交地址
21             xmlHttp.open("GET", "/WEB022/ajaxServlet?name=lisi", true);
22             // 4、发送请求
23             xmlHttp.send();
24         }
25         
26         function fn2() {
27             // 1、创建ajax引擎对象
28             var xmlHttp = new XMLHttpRequest();
29             // 2、为ajax引擎对象绑定监听
30             xmlHttp.onreadystatechange = function() {
31                 if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {
32                     // 5、接受响应数据
33                     var res = xmlHttp.responseText;
34                     document.getElementById("span2").innerHTML = res;
35                 }
36             }
37             // 3、绑定提交地址
38             xmlHttp.open("POST", "/WEB022/ajaxServlet", false);
39             // 4、发送请求(POST提交方式需要设置一个头)
40             xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
41             xmlHttp.send("name=zhangsan");
42         }
43     </script>
44 </head>
45 <body>
46     <input type="button" value="异步访问" onclick="fn1()"><span id="span1"></span>
47     <br>
48     <input type="button" value="同步访问" onclick="fn2()"><span id="span2"></span>
49     <br>
50     <input type="button" value="测试" onclick="alert(661)"><br>
51 </body>
52 </html>

 

JS原生Ajax

标签:form   enc   new   char   ready   ati   其他   str   用户   

原文地址:https://www.cnblogs.com/alphajuns/p/9971736.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!