目录
AJAX 即“Asynchronous Javascript And XML”(异步 JavaScript 和 XML),是指一种创建交互式网页应用的网页开发技术。
AJAX 是一种浏览通过 JS 异步发起请求,局部更新页面的技术。
AJAX 请求的局部更新器,浏览器地址栏不会发生变化,局部更新不会舍弃原来页面的内容。
XMLHttpRequest 用于在后台与服务器交换数据。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。
如需将请求发送到服务器,我们使用 XMLHttpRequest 对象的 open() 和 send() 方法:
open(method,url,async):规定请求的类型、URL 以及是否异步处理请求。
send(string):将请求发送到服务器
Async = true,异步发送请求,需要规定在响应处于 onreadystatechange 事件中的就绪状态时执行的函数
Async=false,将 open() 方法中的第三个参数改为 false
需获得来自服务器的响应,请使用 XMLHttpRequest 对象的 responseText 或 responseXML 属性。
responseText:获取字符串形式的响应数据
可以这样使用:
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
responseXML:获得XML形式的响应数据
可以这样使用:
- xmlDoc=xmlhttp.responseXML;
- txt="";
- x=xmlDoc.getElementsByTagName("ARTIST");
- for (i=0;i
length;i++) - {
- txt=txt + x[i].childNodes[0].nodeValue + "
"; - }
- document.getElementById("myDiv").innerHTML=txt;
当请求被发送到服务器时,我们需要执行一些基于响应的任务。
每当 readyState 改变时,就会触发 onreadystatechange 事件。
readyState 属性存有 XMLHttpRequest 的状态信息。
下面是 XMLHttpRequest 对象的三个重要的属性:
| 属性 | 描述 |
|---|---|
| onreadystatechange | 存储函数(或函数名),每当 readyState 属性改变时,就会调用该函数。 |
| readyState | 存有 XMLHttpRequest 的状态。从 0 到 4 发生变化。
|
| status | 200: "OK" 404: 未找到页面 |
ajax.html,实现的效果是当点击按钮时,div标签里会出现从服务器返回的内容。
- html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
- <html>
- <head>
- <meta http-equiv="pragma" content="no-cache" />
- <meta http-equiv="cache-control" content="no-cache" />
- <meta http-equiv="Expires" content="0" />
- <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
- <title>Insert title heretitle>
- <script type="text/javascript">
- function ajaxRequest() {
- //1、我们首先要创建XMLHttpRequest
- var xmlHttpRequest=new XMLHttpRequest();
- //2、调用open方法设置请求参数
- xmlHttpRequest.open("GET","http://localhost:8080/16_json_ajax_i18n/ajaxServlet?action=javaScriptAjax",true);
-
- //3、在send方法前绑定onreadystatechange事件,处理请求完成后的操作
- xmlHttpRequest.onreadystatechange=function(){
- if(xmlHttpRequest.readyState==4&&xmlHttpRequest.status==200){
- var obj=JSON.parse(xmlHttpRequest.responseText);
- document.getElementById("div01").innerHTML="编号"+obj.id+" 名字"+obj.name;
- }
- }
- //4、调用send方法发送请求
- xmlHttpRequest.send();
- }
- script>
- head>
- <body>
- <button onclick="ajaxRequest()">ajax requestbutton>
- <div id="div01">
- div>
- body>
- html>
使用BaseServlet抽取Servlet对象,在请求中携带名称为action,值为方法名的参数动态调用请求方法。
- public abstract class BaseServlet extends HttpServlet{
- @Override
- protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- doPost(req,resp);
- }
-
- @Override
- protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- //解决请求中文乱码问题
- req.setCharacterEncoding("UTF-8");
- //解决响应中文乱码问题
- resp.setContentType("text/html; charset=UTF-8");
-
- //获取参数action的值
- String action=req.getParameter("action");
-
- try {
- // 匹配指定名称和参数的类的方法,此方法返回的是Method对象
- Method method = this.getClass().getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);
- //调用目标业务方法,这里的 this 是子类
- method.invoke(this,req,resp);
- } catch (Exception e){
- e.printStackTrace();
- }
- }
- }
Servlet代码
- public class AjaxServlet extends BaseServlet{
-
- protected void javaScriptAjax(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
- System.out.println("被调用");
-
- Person person = new Person("qwerty", 12);
-
- //json格式的字符串
- Gson gson = new Gson();
- String personJsonString = gson.toJson(person);
-
- //返回数据
- resp.getWriter().write(personJsonString);
- }
- }
解释:当请求到达AjaxServlet,由于没有 doGet() 方法,会向父类寻找, BaseServlet中有 doGet()方法,调用父类的 doGet()方法,首先获取 action 的值javaScriptAjax,这里的 this是子类,通过反射调用子类名为 javaScriptAjax 的方法。
web.xml
- <servlet>
- <servlet-name>AjaxServletservlet-name>
- <servlet-class>com.servlet.AjaxServletservlet-class>
- servlet>
- <servlet-mapping>
- <servlet-name>AjaxServletservlet-name>
- <url-pattern>/ajaxServleturl-pattern>
- servlet-mapping>