Ajax概述
1.同步与异步
- 同步:客户端与服务器端的请求与响应是一个过程的,也就是说在过程完成前客户端都处于等待卡死状态
- 异步:客户端发送请求,无论服务器是否响应,客户端都可以随意做其他事情。
2.Ajax的运行原理
页面发起请求,会将请求发送给浏览器内核中Ajax引擎,Ajax引擎会提交请求到服务端,在这段时间里,客户端可以任意进行任意操作,直到服务器端将数据返回给Ajax引擎后,会触发你设置的事件,从而执行自定义的js逻辑代码完成某种页面功能。
js原生的ajax
js原生的Ajax其实就是围绕浏览器内置的Ajax引擎对象进行开发的,要使用js原生的Ajax完成异步操作,需要如下步骤
- 创建Ajax引擎对象
- 为Ajax引擎对象绑定监听(监听服务器已将数据响应给引擎)
- 绑定提交地址
- 发送请求
- 接受响应数据
index.html
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
| <!DOCTYPE HTML> <html> <head> <title>index</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page">
<script type="text/javascript"> function fn1(){ var xmlHttp; if(window.XMLHttpRequest){ xmlHttp = new XMLHttpRequest(); }else{ xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); } xmlHttp.onreadystatechange = function(){ if(xmlHttp.readyState==4&&xmlHttp.status==200){ document.getElementById("span1").innerHTML = xmlHttp.responseText; } } xmlHttp.open("post","AjaxServlet",true); xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xmlHttp.send("name=wangsiyuan"); } </script> </head> <body> <input type="button" value="异步访问服务器" onclick="fn1()"> <span id="span1"></span> </body> </html>
|
属性 |
描述 |
onreadystatechange |
存储函数(或函数名),每当readyState属性改变时,就会调用该函数 |
readyState | 存有XMLHttpRequest的状态。从0到4的变化(0:请求未初始化 1:服务器连接已建立 2:请求已处理 3:请求处理中 4:请求已完成,且响应已就绪)
status | 200:”OK” 404:”页面未找到” 500:”服务器错误”…
AjaxServlet.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| package top.code666.ajax01;
import java.io.IOException; import java.io.PrintWriter;
import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;
public class AjaxServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name = (String) request.getParameter("name"); response.getWriter().write(Math.random()+name); }
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doGet(request, response); } }
|
运行结果:

JQuery的Ajax技术(重点)
1.jQuery的get、post方式
- $.get(url,[data],[callback],[type])
- $.post(url,[data],[callback],[type])
url:代表请求的服务器地址
data:代表请求服务端的数据(可以是key=value形式也可以是json格式)
callback:表示服务器端成功响应所触发的函数(只有正常成功返回才执行)
type:表示服务器端返回的数据类型(jQuery会根据指定的类型自动类型转换)
常见的返回类型:text、json、html等
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
| // 这里只贴js代码 <script> function fn1(){ $.get( "/project/ajaxProject", {"name":"zhangsan","age":22}, function(data){ alert(data); }, "text" ); }
function fn1(){ $.post( "/project/ajaxProject", {"name":"zhangsan","age":22}, function(data){ alert(data.name); }, "json" ); } </script>
|
注意:post方法传输中文到服务端不用考虑乱码问题,get方法需要考虑乱码问题
2.jQuery的ajax方式
$.ajax({option1:value1,option2:value2…});
常用的option有如下:
- async:是否异步,默认是true代表异步
- data:发送到服务器的参数,建议使用json格式
- dataType:服务器端返回的数据类型,常用的text和json
- success:成功响应执行的函数,对应的类型是function类型
- type:请求方式,POST/GET
- url:请求服务端地址
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| <script> function fn3(){ $.ajax({ url:"/project/ajaxProject", async:true, type:"POST", data:{"name":"tom","age":22}, success:function(data){ alert(data.name); }, error:function(){ alert("请求失败"); }, dataType:"json" }); } </script>
|
##附
####ajax实现loading效果
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| $.ajax({ type: "post", data: studentInfo, contentType: "application/json", url: "/Home/Submit", beforeSend: function () { $("#submit").attr({ disabled: "disabled" }); }, success: function (data) { if (data == "Success") { clearBox(); } }, complete: function () { $("#submit").removeAttr("disabled"); }, error: function (data) { console.info("error: " + data.responseText); } });
|