Ajax核心知识(1)

XMLHttpRequest对象创建

所有现代浏览器均支持XMLHttpRequest对象( IE5 和 IE6 使用 ActiveXObject)。

XMLHttpRequest用于在后台与服务器交换数据。这意味着可以再不重新加载整个网页的情况下,对网页的某部分进行更新。

XMLHttpRequest对象请求后台

open(mehod,url,async);

规定请求的类型,URL以及是否异步处理请求。

mehod:请求类型;GET或者POST;

url:文件在服务器上的位置。

async:true(异步)或false(同步)

 1 <%@ page language="java" contentType="text/html; charset=utf-8"
 2     pageEncoding="utf-8"%>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <html>
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
 7 <title>Insert title here</title>
 8 </head>
 9 <script type="text/javascript">
10 function loadName(){
11         var xmlHttp;
12         if(window.XMLHttpRequest){
13             xmlHttp=new XMLHttpRequest();
14         }else{
15             xmlHttp=new ActiveXObject( "Microsoft.XMLHTTP ");
16         }
17         xmlHttp.open("get","getAjaxName?name=jack&age=18",true);
18         xmlHttp.send(); 
19 }
20  </script>
21 <body>
22 <div style="text-align: center">
23     <div>
24         <input type="button" value="Ajax获取数据" onclick="loadName()"/>
25         &nbsp;&nbsp;<input type="text" id="name" name="name"/></input>
26     </div>
27 </div>
28 </body>
29 </html>

send(string)将请求发送到服务器。

string:仅用于POST请求

GET还是POST?

与POST相比,GET更加简单也更快,并且在大部分情况下都能使用。

然而,在以下情况下,请使用POST请求:

无法使用缓存文件(更新服务器的文件或者数据库);

向服务器发送大量数据(POST没有数据量限制);

 发送包含未知字符的用户输入时,POST比GET更稳定也更可靠;

setRequestHeader(head,value)

详情求添加HTTP头。

header:规定头名称

value:规定头的值。

xmlhttp:setRequestHeader("content-type","application/x-www-form-urlencoded");

异步 -True或False ?

AJAX指的是异步 javaScript和XML(Asynchronous javaScript and XML).

为True的话,表示的是异步,异步表示的程序请求服务器的同时,程序可以继续执行;能提高系统的运行效率;

为False的话,表示同步,JavaScript会等到服务器响应就绪才继续执行。如果服务器繁忙或缓慢,应用程序会挂起或停止。

我们一般都是用True;

 1 <%@ page language="java" contentType="text/html; charset=utf-8"
 2     pageEncoding="utf-8"%>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <html>
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
 7 <title>Insert title here</title>
 8 </head>
 9 <script type="text/javascript">
10 function loadName(){
11         var xmlHttp;
12         if(window.XMLHttpRequest){
13             xmlHttp=new XMLHttpRequest();
14         }else{
15             xmlHttp=new ActiveXObject( "Microsoft.XMLHTTP ");
16         }
17         xmlHttp.open("post","getAjaxName",true);
18         xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
19         xmlHttp.send("name=jack1&age=19");
20 }
21  </script>
22 <body>
23 <div style="text-align: center">
24     <div>
25         <input type="button" value="Ajax获取数据" onclick="loadName()"/>
26         &nbsp;&nbsp;<input type="text" id="name" name="name"/></input>
27     </div>
28 </div>
29 </body>
30 </html>

XMLHttpRequest对象响应服务器

onreadystatechange事件

当请求被发送到服务器时,我们需要执行一些基于响应的任务。

每当readyState改变时,就会触发 onreadystatechange事件。

readyState属性存有XML  HttpRequest的状态信息。

下面是 XMLRequest对象的三个重要的属性:

onreadystatechange存储函数(或函数名),每当readyState属性改变时,就会调用该函数。

readState

存有XMLHttpRequest的状态,从0到4发生变化:

0:请求为初始化

1:服务器连接已建立

2:请求已接收

3:请求处理中

4:请求已完成,且响应已就绪

status:

200:“OK”

404:未找到页面

在 onreadystatechange时间中,我们规定当服务器响应已做好被处理的准备所执行的任务。

如需获取来自服务器的响应,请使用XMLHttpRequest对象的response或responseXML属性

属性  描述

responseText获得字符串形式的响应数据。

 responseXML获得XML形式的相应数据。(了解即可)

Json格式语法

 1 JSON 对象
 2 {“name”:"张三","age":22}
 3 JSON 数组
 4 {
 5   “student”:[
 6       {"name":"张三","age":22},
 7       {“name”:"李四","age":23},
 8       {"name":"王五",“age”:24}
 9     ]  
10 }
11 JSON嵌套
12 {
13   “student”:[
14       {"name":"张三","age":22,"score":{"chinese":90,"math":100,"english":80}},
15       {“name”:"李四","age":23,"score":{"chinese":80,"math":89,"english":85}},
16       {"name":"王五",“age”:24,"score":{"chinese":75,"math":123,"english":70}}
17     ]  
18 }

把Json串换成Json对象

var dataobj=eval("("+data+")");//转换为json对象

引入Json.lib包!

 ajax.jsp

 1 <%@ page language="java" contentType="text/html; charset=utf-8"
 2     pageEncoding="utf-8"%>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <html>
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
 7 <title>Insert title here</title>
 8 </head>
 9 <script type="text/javascript">
10 function loadInfo(){
11         var xmlHttp;
12         if(window.XMLHttpRequest){
13             xmlHttp=new XMLHttpRequest();
14         }else{
15             xmlHttp=new ActiveXObject( "Microsoft.XMLHTTP ");
16         }
17         alert("readState状态:"+xmlHttp.readyState+";status状态:"+xmlHttp.status);
18         xmlHttp.onreadystatechange=function(){
19             alert("readState状态"+xmlHttp.readyState+";status状态"+xmlHttp.status);
20             if(xmlHttp.readyState==4&&xmlHttp.status==200){
21                 alert(xmlHttp.responseText);
22                 var dataobj=eval("("+xmlHttp.responseText+")");
23                 alert("name="+dataobj.name);
24                 alert("age="+dataobj.age);
25                 document.getElementById("name").value=dataobj.name;
26                 document.getElementById("age").value=dataobj.age;
27             }
28         };
29         xmlHttp.open("get","getAjaxInfo",true);
30         xmlHttp.send();     
31 }
32  </script>
33 <body>
34 <div style="text-align: center">
35     <div>
36         <input type="button" value="Ajax获取信息" onclick="loadInfo()"/>
37         &nbsp;&nbsp;姓名:<input type="text" id="name" name="name"/>
38         &nbsp;&nbsp;年龄:<input type="text" id="age" name="age"/>
39     </div>
40 </div>
41 </body>

web.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
 3   <display-name>HeadFirstAjaxJson</display-name>
 4   <welcome-file-list>
 5     <welcome-file>index.html</welcome-file>
 6     <welcome-file>index.htm</welcome-file>
 7     <welcome-file>index.jsp</welcome-file>
 8     <welcome-file>default.html</welcome-file>
 9     <welcome-file>default.htm</welcome-file>
10     <welcome-file>default.jsp</welcome-file>
11   </welcome-file-list>
12   <servlet>
13       <servlet-name>getAjaxInfoServlet</servlet-name>
14     <servlet-class>com.java1234.web.GetAjaxInfoServlet</servlet-class>
15   </servlet>
16   <servlet-mapping>
17       <servlet-name>getAjaxInfoServlet</servlet-name>
18       <url-pattern>/getAjaxInfo</url-pattern>
19   </servlet-mapping>
20 </web-app>

GetajaxInfoServlet 1 package com.java1234.web;

 2 
 3 import java.io.IOException;
 4 import java.io.PrintWriter;
 5 
 6 import javax.servlet.ServletException;
 7 import javax.servlet.http.HttpServlet;
 8 import javax.servlet.http.HttpServletRequest;
 9 import javax.servlet.http.HttpServletResponse;
10 
11 public class GetAjaxInfoServlet extends HttpServlet{
12 
13     /**
14      * 
15      */
16     private static final long serialVersionUID = 1L;
17 
18     @Override
19     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
20         // TODO Auto-generated method stub
21         this.doPost(request, response);
22     }
23 
24     @Override
25     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
26         // TODO Auto-generated method stub
27         response.setContentType("text/Html;charset=utf-8");
28         PrintWriter out=response.getWriter();
29         String ResultJson="{\"name\":\"张三\",\"age\":22}";
        或者这样写:

                JSONObject ResultJson=new JSONObject();
                ResultJson.put("name","张三");
          ResultJson.put("age", 21);

30         out.println(ResultJson);
31         out.flush();
32         out.close();
33     }
34 }

猜你喜欢

转载自www.cnblogs.com/zyxsblogs/p/10014577.html
今日推荐