zoukankan      html  css  js  c++  java
  • 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 }

     研究数组嵌套:

      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 import net.sf.json.JSONArray;
     12 import net.sf.json.JSONObject;
     13 
     14 public class GetAjaxInfoServlet extends HttpServlet{
     15 
     16     /**
     17      * 
     18      */
     19     private static final long serialVersionUID = 1L;
     20 
     21     @Override
     22     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     23         // TODO Auto-generated method stub
     24         this.doPost(request, response);
     25     }
     26 
     27     @Override
     28     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     29         // TODO Auto-generated method stub
     30         String action=request.getParameter("action");
     31         if("resultJson".equals(action)){
     32             doGetResultJson(request,response);
     33         }else if("JsonArray".equals(action)){
     34             doGetJsonArray(request,response);
     35         }
     36     }
     37     private void doGetResultJson(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     38         response.setContentType("text/Html;charset=utf-8");
     39         PrintWriter out=response.getWriter();
     40         //String ResultJson="{"name":"张三","age":22}";
     41         JSONObject ResultJson=new JSONObject();
     42         ResultJson.put("name","张三");
     43         ResultJson.put("age", 21);
     44         out.println(ResultJson);
     45         out.flush();
     46         out.close();
     47     }
     48     private void doGetJsonArray(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
     49         response.setContentType("text/Html;charset=utf-8");
     50         PrintWriter out=response.getWriter();
     51         /*{
     52              5   “student”:[
     53              6       {"name":"张三","age":22},
     54              7       {“name”:"李四","age":23},
     55              8       {"name":"王五",“age”:24}
     56              9     ]  
     57             10 }
     58 
     59         *{
     60   “student”:[
     61        {"name":"张三","age":22,"score":{"chinese":90,"math":100,"english":80}},
     62        {“name”:"李四","age":23,"score":{"chinese":80,"math":89,"english":85}},
     63        {"name":"王五",“age”:24,"score":{"chinese":75,"math":123,"english":70}}
     64      ]  
     65  }
     66         *
     67         *
     68         *
     69         *
     70         */
     71         
     72         JSONObject ResultJson=new JSONObject();
     73         JSONArray JsonArrays=new JSONArray();
     74         
     75         JSONObject jsonScore1=new JSONObject();
     76             jsonScore1.put("chinese", 90);
     77             jsonScore1.put("math", 100);
     78             jsonScore1.put("english", 80);
     79         JSONObject jsonScore2=new JSONObject();
     80             jsonScore2.put("chinese", 80);
     81             jsonScore2.put("math", 100);
     82             jsonScore2.put("english", 50);
     83         JSONObject jsonScore3=new JSONObject();
     84             jsonScore3.put("chinese", 99);
     85             jsonScore3.put("math", 102);
     86             jsonScore3.put("english", 100);
     87         JSONObject ResultJson1=new JSONObject();
     88          ResultJson1.put("name", "张三");
     89          ResultJson1.put("age", 22);
     90          ResultJson1.put("score", jsonScore1);
     91         JSONObject ResultJson2=new JSONObject();
     92             ResultJson2.put("name", "李四");
     93             ResultJson2.put("age",23);
     94             ResultJson2.put("score", jsonScore2);
     95         JSONObject ResultJson3=new JSONObject();
     96             ResultJson3.put("name", "王五");
     97             ResultJson3.put("age", 25);
     98             ResultJson3.put("score", jsonScore3);
     99             
    100         JsonArrays.add(ResultJson1);
    101         JsonArrays.add(ResultJson2);
    102         JsonArrays.add(ResultJson3);
    103         ResultJson.put("students", JsonArrays);
    104         out.println(ResultJson);
    105         out.flush();
    106         out.close();
    107     }
    108 }

    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?action=resultJson",true);
    30         xmlHttp.send();     
    31 }
    32 
    33 
    34 function loadInfo2(){
    35     var xmlHttp;
    36     if(window.XMLHttpRequest){
    37         xmlHttp=new XMLHttpRequest();
    38     }else{
    39         xmlHttp=new ActiveXObject( "Microsoft.XMLHTTP ");
    40     }
    41     xmlHttp.onreadystatechange=function(){
    42         if(xmlHttp.readyState==4&&xmlHttp.status==200){
    43             alert(xmlHttp.responseText);
    44             var dataobj=eval("("+xmlHttp.responseText+")");
    45             var st=document.getElementById("studentTable");
    46             var newTr;//
    47             var newTd0;//第一列
    48             var newTd1;//第二列
    49             var newTd2;//第二列
    50             for(var i=0;i<dataobj.students.length;i++){
    51                 var student=dataobj.students[i];
    52                 newTr=st.insertRow();
    53                 newTd0=newTr.insertCell();
    54                 newTd1=newTr.insertCell();
    55                 newTd2=newTr.insertCell();
    56                 newTd0.innerHTML=student.name;
    57                 newTd1.innerHTML=student.age;
    58                 newTd2.innerHTML="语文:"+student.score.chinese+",数学:"+student.score.math+",英语:"+student.score.english;
    59             }
    60         }
    61     };
    62     xmlHttp.open("get","getAjaxInfo?action=JsonArray",true);
    63     xmlHttp.send();     
    64 }
    65  </script>
    66 <body>
    67 <div style="text-align: center">
    68     <div>
    69         <input type="button" value="Ajax获取信息" onclick="loadInfo()"/>
    70         &nbsp;&nbsp;姓名:<input type="text" id="name" name="name"/>
    71         &nbsp;&nbsp;年龄:<input type="text" id="age" name="age"/>
    72     </div>
    73     <div style="margin-top: 20px;text-align: center">
    74         <input type="button" value="Ajax获取信息2" onclick="loadInfo2()">
    75         <table id="studentTable" align="center" border="1" cellpadding="0px" style="margin-top: 10px">
    76             <tr>
    77                 <th>姓名</th><th>年龄</th><th>得分</th>
    78             </tr>
    79         </table>
    80     </div>
    81 </div>
    82 </body>
    83 </html>
  • 相关阅读:
    Ajax省市区无刷新单表联动查询
    Hadoop2.0、YARN技术大数据视频教程
    零基础DNET B/S开发软件工程师培训视频教程
    零基础DNET CS开发视频教程
    HTML5开发框架PhoneGap实战视频教程
    Web前端开发视频教程
    FluentData 轻量级.NET ORM持久化技术详解
    前端 MVVM 框架KnockOut.JS深入浅出视频教程
    ASP.NET Web开发项目实战视频教程
    零基础到CS开发高手通用权限管理系统全程实录
  • 原文地址:https://www.cnblogs.com/zyxsblogs/p/10014577.html
Copyright © 2011-2022 走看看