Ajax基础

来源:互联网 发布:银行存款怎样划算知乎 编辑:程序博客网 时间:2024/06/06 02:17

Ajax

package com.java1234.web;


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 GetAjaxNameServlet extends HttpServlet{


/**
 * 
 */
private static final long serialVersionUID = 1L;


@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}


@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out=response.getWriter();
out.println("波多野");
out.flush();
out.close();
}


}


package com.java1234.web;


import java.io.IOException;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class GetNameServlet extends HttpServlet{


/**
 * 
 */
private static final long serialVersionUID = 1L;


@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}


@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setAttribute("name", "波多野");
request.getRequestDispatcher("common.jsp").forward(request, response);
}
}


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
  <%
  Object obj = application.getAttribute("count2");
     if(obj==null){
   Integer count = 1;
   application.setAttribute("count2",count);
   
   }else{
   Integer count = (Integer)obj;
   count++;
   application.setAttribute("count2",count);
   }
   %>
</head>
<link href="css/slide.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery.SuperSlide.2.1.1.js"></script>
<script type="text/javascript">
$(function(){
$("#focus").hover(function(){$("#focus-prev,#focus-next").show();},function(){$("#focus-prev,#focus-next").hide();});
$("#focus").slide({ 
mainCell:"#focus-bar-box ul",
targetCell:"#focus-title a",
titCell:"#focus-num a",
prevCell:"#focus-prev",
nextCell:"#focus-next",
effect:"left",
easing:"easeInOutCirc",
autoPlay:true,
delayTime:200
})
})

function loadName(){
var xmlHttp;
if(window.XMLHttpRequest){//有没有有的话就new一个
xmlHttp=new XMLHttpRequest();
}else{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttp.onreadystatechange=function(){//监听一种状态
if(xmlHttp.readyState==4 && xmlHttp.status==200){//后台已经请求成功并且返回数据
document.getElementById("name").value=xmlHttp.responseText;//把返回的数据给dom节点赋值
}
};
xmlHttp.open("get","getAjaxName",true);//get方式一般用 ajaxName请求后台的数据true异步代码还可以继续,不用等代码执行完毕
xmlHttp.send();
}
</script>
<body>
<div style="text-align: center;">
<div style="padding: 10px;"><input type="button" style="border: 1px solid red;" value="获取姓名" onclick="loadName()"/>&nbsp;&nbsp;<input type="text" id="name" name="name" value="${name }" style="border-bottom: 1px solid red"/>&nbsp;&nbsp;页面刷新次数:<font color="red">${count2 }</font></div>
</div>
<div id="focus">
<div class="hd">
<div class="focus-title" id="focus-title">
    <a href="http://www.java1234.com"><span class="title">《王的女人》</span>于正版霸王别姬 陈乔恩变腹黑大战情敌袁姗姗</a>
    <a href="http://www.java1234.com"><span class="title">《盲探》</span>刘德华、郑秀文、杜琪峰香港电影铁三角十年归来</a>
    <a href="http://www.java1234.com"><span class="title">《爸爸去哪儿》</span>众星爸厨艺比拼犯难(2013-10-18期)</a>
    <a href="http://www.java1234.com"><span class="title">《到爱的距离》</span>李晨张馨予谱写爱之终曲</a>
    <a href="http://www.java1234.com"><span class="title">《天台》</span>周杰伦自导自演  传递超屌正能量</a>
</div>
    <a class="hdicon" href="http://www.java1234.com"></a>
    </div>
    <div class="focus-bar-box" id="focus-bar-box">
      <ul class="focus-bar">
        <li><a href="http://www.java1234.com"><img src="images/01.jpg"></a></li>
        <li><a href="http://www.java1234.com"><img src="images/02.jpg"></a></li>
        <li><a href="http://www.java1234.com"><img src="images/03.jpg"></a></li>
        <li><a href="http://www.java1234.com"><img src="images/04.jpg"></a></li>
        <li><a href="http://www.java1234.com"><img src="images/05.jpg"></a></li>
      </ul>
    </div>
    <a href="http://www.java1234.com" class="btn-prev" onclick="return false;" hidefocus="" id="focus-prev"></a>
    <a href="http://www.java1234.com" class="btn-next" onclick="return false;" hidefocus="" id="focus-next"></a>
  <div class="ft">
    <div class="ftbg"></div>
    <div id="focus-num" class="change">
        <a class=""></a>
        <a class=""></a>
        <a class=""></a>
        <a class=""></a>
        <a class=""></a>
    </div>
  </div>
</div>
</body>
</html>


<?xml version="1.0" encoding="UTF-8"?>
<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">
  <display-name>HeadFirstAjaxJson</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
  <servlet>
   <servlet-name>getNameServlet</servlet-name>
   <servlet-class>com.java1234.web.GetNameServlet</servlet-class>
  </servlet>
  
  <servlet-mapping>
   <servlet-name>getNameServlet</servlet-name>
   <url-pattern>/getName</url-pattern>
  </servlet-mapping>
  
  <servlet>
   <servlet-name>getAjaxNameServlet</servlet-name>
   <servlet-class>com.java1234.web.GetAjaxNameServlet</servlet-class>
  </servlet>
  
  <servlet-mapping>
   <servlet-name>getAjaxNameServlet</servlet-name>
   <url-pattern>/getAjaxName</url-pattern>//请求后台的一个路径
  </servlet-mapping>
</web-app>


//什么是 AJAX ?
//AJAX = 异步 JavaScript 和 XML。
AJAX 是一种用于创建快速动态网页的技术。
通过在后台与服务器进行少量数据交换,AJAX 可以使网页实现异步更新。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。
//传统的网页(不使用 AJAX)如果需要更新内容,必需重载整个网页面。
//有很多使用 AJAX 的应用程序案例:新浪微博、Google 地图、开心网等等。


AJAX 实例解释
//上面的 AJAX 应用程序包含一个 div 和一个按钮。
//div 部分用于显示来自服务器的信息。当按钮被点击时,它负责调用名为 loadXMLDoc() 的函数:


<html>
 <body>
<div id="myDiv"><h3>Let AJAX change this text</h3></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>


</body>
</html>
接下来,在页面的 head 部分添加一个 <script> 标签。该标签中包含了这个 loadXMLDoc() 函数:


<head>
<script type="text/javascript">
function loadXMLDoc()
{
.... AJAX script goes here ...
}
</script>
</head>
XMLHttpRequest 对象
所有现代浏览器均支持 XMLHttpRequest 对象(IE5 和 IE6 使用 ActiveXObject)。
XMLHttpRequest 用于在后台与服务器交换数据。这意味着可以在不重新加载整个网页的情况下,对网页的某部分进行更新。
创建 XMLHttpRequest 对象
所有现代浏览器(IE7+、Firefox、Chrome、Safari 以及 Opera)均内建 XMLHttpRequest 对象。
创建 XMLHttpRequest 对象的语法:
variable=new XMLHttpRequest();
老版本的 Internet Explorer (IE5 和 IE6)使用 ActiveX 对象:
variable=new ActiveXObject("Microsoft.XMLHTTP");
为了应对所有的现代浏览器,包括 IE5 和 IE6,请检查浏览器是否支持 XMLHttpRequest 对象。如果支持,则创建 XMLHttpRequest 对象。如果不支持,则创建 ActiveXObject :
var xmlhttp;
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
XMLHttpRequest 对象用于和服务器交换数据。
向服务器发送请求
如需将请求发送到服务器,我们使用 XMLHttpRequest 对象的 open() 和 send() 方法:
xmlhttp.open("GET","test1.txt",true);
xmlhttp.send();
ET 还是 POST?
与 POST 相比,GET 更简单也更快,并且在大部分情况下都能用。
然而,在以下情况中,请使用 POST 请求:
无法使用缓存文件(更新服务器上的文件或数据库)
向服务器发送大量数据(POST 没有数据量限制)
发送包含未知字符的用户输入时,POST 比 GET 更稳定也更可靠
GET 请求
一个简单的 GET 请求:
xmlhttp.open("GET","demo_get.asp",true);
xmlhttp.send();
在上面的例子中,您可能得到的是缓存的结果。
为了避免这种情况,请向 URL 添加一个唯一的 ID:
xmlhttp.open("GET","demo_get.asp?t=" + Math.random(),true);
xmlhttp.send();
如果您希望通过 GET 方法发送信息,请向 URL 添加信息:
xmlhttp.open("GET","demo_get2.asp?fname=Bill&lname=Gates",true);
xmlhttp.send();
POST 请求
一个简单 POST 请求:
xmlhttp.open("POST","demo_post.asp",true);
xmlhttp.send();
如果需要像 HTML 表单那样 POST 数据,请使用 setRequestHeader() 来添加 HTTP 头。然后在 send() 方法中规定您希望发送的数据:
xmlhttp.open("POST","ajax_test.asp",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("fname=Bill&lname=Gates");
url - 服务器上的文件
open() 方法的 url 参数是服务器上文件的地址:
xmlhttp.open("GET","ajax_test.asp",true);
该文件可以是任何类型的文件,比如 .txt 和 .xml,或者服务器脚本文件,比如 .asp 和 .php (在传回响应之前,能够在服务器上执行任务)。
异步 - True 或 False?
AJAX 指的是异步 JavaScript 和 XML(Asynchronous JavaScript and XML)。
XMLHttpRequest 对象如果要用于 AJAX 的话,其 open() 方法的 async 参数必须设置为 true:
xmlhttp.open("GET","ajax_test.asp",true);
对于 web 开发人员来说,发送异步请求是一个巨大的进步。很多在服务器执行的任务都相当费时。AJAX 出现之前,这可能会引起应用程序挂起或停止。
通过 AJAX,JavaScript 无需等待服务器的响应,而是:
在等待服务器响应时执行其他脚本
当响应就绪后对响应进行处理
Async = true
当使用 async=true 时,请规定在响应处于 onreadystatechange 事件中的就绪状态时执行的函数:
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","test1.txt",true);
xmlhttp.send();
Async = false
如需使用 async=false,请将 open() 方法中的第三个参数改为 false:
xmlhttp.open("GET","test1.txt",false);
我们不推荐使用 async=false,但是对于一些小型的请求,也是可以的。
请记住,JavaScript 会等到服务器响应就绪才继续执行。如果服务器繁忙或缓慢,应用程序会挂起或停止。
注xmlhttp.open("GET","test1.txt",false);
xmlhttp.send();
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;释:当您使用 async=false 时,请不要编写 onreadystatechange 函数 - 把代码放到 send() 语句后面即可:
xmlhttp.open("GET","test1.txt",false);
xmlhttp.send();
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
responseText 属性
如果来自服务器的响应并非 XML,请使用 responseText 属性。
responseText 属性返回字符串形式的响应,因此您可以这样使用:
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
responseXML 属性
如果来自服务器的响应是 XML,而且需要作为 XML 对象进行解析,请使用 responseXML 属性:
请求 books.xml 文件,并解析响应:
xmlDoc=xmlhttp.responseXML;
txt="";
x=xmlDoc.getElementsByTagName("ARTIST");
for (i=0;i<x.length;i++)
  {
  txt=txt + x[i].childNodes[0].nodeValue + "<br />";
  }
document.getElementById("myDiv").innerHTML=txt;
onreadystatechange 事件
当请求被发送到服务器时,我们需要执行一些基于响应的任务。
每当 readyState 改变时,就会触发 onreadystatechange 事件。
readyState 属性存有 XMLHttpRequest 的状态信息。
下面是 XMLHttpRequest 对象的三个重要的属性:
在 onreadystatechange 事件中,我们规定当服务器响应已做好被处理的准备时所执行的任务。
当 readyState 等于 4 且状态为 200 时,表示响应已就绪:
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  }
注释:onreadystatechange 事件被触发 5 次(0 - 4),对应着 readyState 的每个变化。
使用 Callback 函数
callback 函数是一种以参数形式传递给另一个函数的函数。
如果您的网站上存在多个 AJAX 任务,那么您应该为创建 XMLHttpRequest 对象编写一个标准的函数,并为每个 AJAX 任务调用该函数。
该函数调用应该包含 URL 以及发生 onreadystatechange 事件时执行的任务(每次调用可能不尽相同):
function myFunction()
{
loadXMLDoc("ajax_info.txt",function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
    }
  });
}


Ajax核心基础

<?xml version="1.0" encoding="UTF-8"?>
<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">
  <display-name>HeadFirstAjaxJsonChap02</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
  <servlet>
   <servlet-name>getAjaxNameServlet</servlet-name>
   <servlet-class>com.java1234.web.GetAjaxNameServlet</servlet-class>
  </servlet>
  
  <servlet-mapping>
   <servlet-name>getAjaxNameServlet</servlet-name>
   <url-pattern>/getAjaxName</url-pattern>
  </servlet-mapping>
</web-app>


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
function loadName(){
var xmlHttp;
if(window.XMLHttpRequest){
xmlHttp=new XMLHttpRequest();//XMLHttpRequest之所以能异步加载
}else{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
alert("readState状态:"+xmlHttp.readyState+";status状态:"+xmlHttp.status);
xmlHttp.onreadystatechange=function(){//基于响应的任务当readyState改变会触发onreadystatechange事件5种状态请求已完成且响应已就绪方法属性重写
alert("readState状态:"+xmlHttp.readyState+";status状态:"+xmlHttp.status);
if(xmlHttp.readyState==4 && xmlHttp.status==200){
alert(xmlHttp.responseText);//获取来自服务器的响应,使用XMLHttpRequest对象的responseText属性
document.getElementById("name").value=xmlHttp.responseText;//值赋给value
}
};
// xmlHttp.open("get", "getAjaxName?name=jack&age=11", true);
// xmlHttp.open("post", "getAjaxName?name=jack&age=11", true);
// xmlHttp.send();

    xmlHttp.open("post", "getAjaxName", true);//干来干去只会做一件事情同步等待服务器响应
    xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");//模拟html发送像form提交向请求添加html头
    xmlHttp.send("name=jack&age=11");//将请求发送到服务器有参数仅用于post使用post无法使用缓存文件服务器发送大量数据包含未知字符的用户输入
}
</script>
</head>
<body>
<div style="text-align: center;">
<div><input type="button" onclick="loadName()" value="Ajax获取数据"/>&nbsp;&nbsp;<input type="text" id="name" name="name" /></div>//onclick调用方法
</div>
</body>
</html>


package com.java1234.web;


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 GetAjaxNameServlet extends HttpServlet{


/**
 * 
 */
private static final long serialVersionUID = 1L;


@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}


@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name=request.getParameter("name");
String age=request.getParameter("age");
System.out.println("name="+name);
System.out.println("age="+age);
response.setContentType("text/html;charset=utf-8");//返回类型
PrintWriter out=response.getWriter();//向页面写内容
out.println("ajax返回的文本");
out.flush();
out.close();
}




}




Ajax的原理
      通过XMLHttpRequest对象来向服务器发送异步请求,从服务器获得数据,用JavaScript来操作DOM从而更新页面。
    特点
提交:不用向服务器提交整个页面
返回:不再是整个页面,而是XML,JSON等数据形式
效果:局部更新网页。
       XMLHttpRequest对象是Ajax技术的核心。
    功能
       一套可以在javascript等脚本语言中通过http协议传送或接收XML及其他数据的一套API。
用法步骤:
       在做项目的过程中,搜索框的联想功能中用到了Ajax技术,因为当时这个联想功能是属于公共部分,一个人做好,其他系统直接用,而且自己当时没学习Ajax,所以就直接按着文档去实现。现在趁着总结,结合这个联想功能的js文件,来总结XMLHttpRequest的五步使用法。
       /*1.针对不同浏览器创建XMLHttpRequest对象*/  
  
 if(window.XMLHttpRequest){    
     //alert("IE7,IE8,FireFox");    
    xmlhttp =new XMLHttpRequest();   
    //针对某些特定版本的mozillar浏览器的BUG进行修正    
    //具体来说:浏览器是通过MIME Type来决定什么内容用什么形式显示   
    //如果来自服务器的响应没有 XML mime-type 头部,则一些版本的 Mozilla 浏览器不能正常运行。  
    //对于这种情况,httpRequest.overrideMimeType('text/xml'); 语句将覆盖发送给服务器的头部,强制 text/xml 作为 mime-type。   
    if(xmlhttp.overrideMimeType){    
        xmlhttp.overrideMimeType("text/xml");    
    }    
}else if(window.ActiveXObject){    
    //alert("IE6,IE5.5,IE5");    
    var activexName=["MSXML2.XMLHTTP.6.0","MSXML2.XMLHTTP.5.0",    
    "MSXML2.XMLHTTP.4.0","MSXML2.XMLHTTP.3.0",    
    "MSXML2.XMLHTTP","Miscrosoft XMLHTTP"];    
    for(var i=0;i<activexName.length;i++) {    
         try{    
             xmlhttp=new ActiveXObject(activexName[i]);    
             break;    
        }catch(e){    
                                
        }    
    }    
}    
if(xmlhttp == undefined || xmlhttp == null){    
    alert("当前浏览器不支持创建XMLHttpRequest对象,请更换浏览器");    
     return;    
}    
/*2.在XMLHttpRequest对象上注册回调函数*/  
       xmlhttp.onreadystatechange=callback;    
//XMLHttpRequest对象有readyState属性和onreadystatechange属性(函数),当readyState属性改变时,就会调用onreadystatechange  
// 0: 请求未初始化  
// 1: 服务器连接已建立  
// 2: 请求已接收  
// 3: 请求处理中  
// 4: 请求已完成,且响应已就绪  
//当onreadystatechange触发时,就会调用callback函数  
/*3.使用open方法设置和服务器端交互的基本信息*/  
       
   //GET方式交互                    
xmlhttp.open("GET","AJAX?name=" + userName,true);    
              
//POST方式交互                   
xmlhttp.open("POST","AJAX",true);    
//POST方式交互所需增加的代码    
xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded")      
    /*4.设置发送的数据,开始和服务器端交互 */     
       //GET方式    
    xmlhttp.send(null);    
        
    //POST方式    
    xmlhttp.send("name=" + userName);    
/*5.更新界面*/  
  
//在回调函数中判断交互是否结束,响应是否正确,并根据需要获取服务器返回的数据,并更新页面  
          
function callback(){  
//判断和服务器端的交互是否完成,还要判断服务器端是否正确返回了数据    
    if(xmlhttp.readyState == 4){    
    //表示和服务器端的交互已经完成    
            if(xmlhttp.status == 200){    
            //表示服务器的是响应代码是200,正确返回了数据    
            var message=xmlhttp.responseText;    
            //XML数据对应的DOM对象的接受方法    
            //使用的前提是,服务器端需要设置contenttype为text/xml    
                       
            //记忆像div标签中填充文本内容的方法    
            var div=document.getElementById("message");    
            div.innerHTML=message;    
              
   }    
}  
       五步法封装:
        在实际使用XMLHTTPRequest当中,不能每次都创建对象,我们需要将公共部分抽象成“类”,在用的时候,我们直接调用对象的属性,方法,并传入相应的参数即可。
       //创建一个"类",这个"类"具有XMLHTTP属性  
function CallBackObject()  
{  
    this.XmlHttp = this.GetHttpObject();  
}  
// 通过原型设置这个类的其他属性:  
//通过GetHTTPObject获得XMLHTTPRequest对象,此属性中封装的是第一步  
CallBackObject.prototype.GetHttpObject = function()  
{   
  var xmlhttp;  
  // if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {  
    // try {  
      // xmlhttp = new XMLHttpRequest();  
    // } catch (e) {  
      // xmlhttp = false;  
    // }  
  // }  
   try{    
        //对于Firefox和Opera等浏览器    
        xmlhttp=new XMLHttpRequest();    
        //有此版本的Mozilla浏览器在处理服务器返回的包含XML mime-type头部信息内容时会出错。      
        //所以,为了确保返回内容是text/xml信息,需要包含下面的语句。      
        if(xmlhttp.overrideMimeType)      
        {      
               xmlhttp.overrideMimeType("text/xml");      
        }      
       }catch(e){  //对于IE浏览器    
                var activexName=new Array('Msxml2.XMLHTTP.7.0',      
                              'Msxml2.XMLHTTP.6.0',     
                              'Msxml2.XMLHTTP.5.0',      
                                          'Msxml2.XMLHTTP.4.0',      
                                          'Msxml2.XMLHTTP.3.0',      
                                          'Msxml2.XMLHTTP',      
                                          'Micrsoft.XMLHTTP');      
                var success=false;      
                for(var i=0;i<activexName.length && !success;i++){      
                    try{      
                        xmlhttp=new ActiveXObject(activexName[i]);      
                        success=true;      
                        break;    
                    }catch(e){      
                              
                    }      
                          
                }      
                if(!success){      
                    alert('Unable to create XMLHttpRequest.');      
                }      
            }   
        return xmlhttp;           
        }     
   
}  
 //DoCallBack封装第二步,第三和第四步  
CallBackObject.prototype.DoCallBack = function(URL)  
{   
  if( this.XmlHttp )  
  {  
    if( this.XmlHttp.readyState == 4 || this.XmlHttp.readyState == 0 )  
    {  
      var oThis = this;  
      this.XmlHttp.open('POST', URL);  
      this.XmlHttp.onreadystatechange = function(){ oThis.ReadyStateChange(); };  
      this.XmlHttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');  
      this.XmlHttp.send(null);  
    }  
  }  
}  
   
CallBackObject.prototype.AbortCallBack = function()  
{  
  if( this.XmlHttp )  
    this.XmlHttp.abort();  
}  
   
CallBackObject.prototype.OnLoading = function()  
{  
  // Loading  
}  
   
CallBackObject.prototype.OnLoaded = function()  
{  
  // Loaded  
}  
   
CallBackObject.prototype.OnInteractive = function()  
{  
  // Interactive  
}  
   
CallBackObject.prototype.OnComplete = function(responseText, responseXml)  
{  
  // Complete  
}  
   
CallBackObject.prototype.OnAbort = function()  
{  
  // Abort  
}  
   
CallBackObject.prototype.OnError = function(status, statusText)  
{  
  // Error  
}  
 //封装第五步,在回调函数中判断交互是否结束,响应是否正确,并根据需要获取服务器返回的数据,并更新页面  
CallBackObject.prototype.ReadyStateChange = function()  
{  
  if( this.XmlHttp.readyState == 1 )  
  {  
    this.OnLoading();  
 }  
  else if( this.XmlHttp.readyState == 2 )  
  {  
   this.OnLoaded();  
  }  
  else if( this.XmlHttp.readyState == 3 )  
  {  
   this.OnInteractive();  
  }  
  else if( this.XmlHttp.readyState == 4 )  
  {  
   if( this.XmlHttp.status == 0 )  
      this.OnAbort();  
    else if( this.XmlHttp.status == 200 && this.XmlHttp.statusText == "OK" )  
      this.OnComplete(this.XmlHttp.responseText, this.XmlHttp.responseXML);  
    else  
      this.OnError(this.XmlHttp.status, this.XmlHttp.statusText, this.XmlHttp.responseText);     
  }  
}  
       
       
 Json

      //返回结构化的格式 key name用“”:value对象{}括起来,数组[]


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
function loadInfo(){
var xmlHttp;
if(window.XMLHttpRequest){
xmlHttp=new XMLHttpRequest();
}else{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState==4 && xmlHttp.status==200){
alert(xmlHttp.responseText);//获取json串
var dataObj=eval("("+xmlHttp.responseText+")");//把json传转为json对象后台处理
alert(dataObj.name);
alert(dataObj.age);
document.getElementById("name").value=dataObj.name;//塞入文本框
document.getElementById("age").value=dataObj.age;
}
};
xmlHttp.open("get", "getAjaxInfo?action=jsonObject", true);//action改一下action共用servlet



    xmlHttp.send();
}

function loadInfo2(){
var xmlHttp;
if(window.XMLHttpRequest){
xmlHttp=new XMLHttpRequest();
}else{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState==4 && xmlHttp.status==200){
alert(xmlHttp.responseText);
var dataObj=eval("("+xmlHttp.responseText+")");
var st=document.getElementById("studentTable");//获取表格对象 id
alert(dataObj.students.length);
var newTr; // 行
var newTd0; // 第一列
var newTd1; // 第二列
var newTd2; // 第三列
for(var i=0;i<dataObj.students.length;i++){
var student=dataObj.students[i];//遍历多少行取数据
newTr=st.insertRow();//插入一行
newTd0=newTr.insertCell();
newTd1=newTr.insertCell();
newTd2=newTr.insertCell();
newTd0.innerHTML=student.name;
newTd1.innerHTML=student.age;
newTd2.innerHTML="语文:"+student.score.chinese+",数学:"+student.score.math+",英语:"+student.score.english;//对象的级联
}
}
};
// xmlHttp.open("get", "getAjaxInfo?action=jsonArray", true);
xmlHttp.open("get", "getAjaxInfo?action=jsonNested", true);
    xmlHttp.send();
}
</script>
</head>
<body>
<div style="text-align: center;">
<div><input type="button" onclick="loadInfo()" value="Ajax获取信息"/>&nbsp;&nbsp;姓名:<input type="text" id="name" name="name" />&nbsp;&nbsp;年龄:<input type="text" id="age" name="age" /></div>
<div style="margin-top: 20px;">
<input type="button" onclick="loadInfo2()" value="Ajax获取信息2"><br/>
<table id="studentTable" align="center" border="1px;" cellpadding="0px;">
<tr>
<th>姓名</th><th>年龄</th><th>得分</th>
</tr>
</table>
</div>
</div>
</body>
</html>


<?xml version="1.0" encoding="UTF-8"?>
<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">
  <display-name>HeadFirstAjaxJsonChap02</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
  <servlet>
   <servlet-name>getAjaxInfoServlet</servlet-name>
   <servlet-class>com.java1234.web.GetAjaxInfoServlet</servlet-class>
  </servlet>
  
  <servlet-mapping>
   <servlet-name>getAjaxInfoServlet</servlet-name>
   <url-pattern>/getAjaxInfo</url-pattern>
  </servlet-mapping>
</web-app>


package com.java1234.web;


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;


import net.sf.json.JSONArray;
import net.sf.json.JSONObject;


public class GetAjaxInfoServlet extends HttpServlet{


/**
 * 
 */
private static final long serialVersionUID = 1L;


@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}


@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
String action=request.getParameter("action");//根据action判断调用的是哪个请求
if("jsonObject".equals(action)){
this.getJsonObject(request, response);
}else if("jsonArray".equals(action)){
this.getJsonArray(request, response);
}else if("jsonNested".equals(action)){
this.getJsonNested(request, response);
}

}



private void getJsonObject(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out=response.getWriter();
// String resultJson="{\"name\":\"张三\",\"age\":22}";返回json串有引号加\变引号
JSONObject resultJson=new JSONObject();//lib面向对象写法
resultJson.put("name", "张三");
resultJson.put("age", 22);
out.println(resultJson);
out.flush();
out.close();
}

private void getJsonArray(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out=response.getWriter();
JSONObject resultJson=new JSONObject();
JSONArray jsonArray=new JSONArray();
JSONObject jsonObject1=new JSONObject();
jsonObject1.put("name", "张三");
jsonObject1.put("age", 22);
JSONObject jsonObject2=new JSONObject();
jsonObject2.put("name", "李四");
jsonObject2.put("age", 23);
JSONObject jsonObject3=new JSONObject();
jsonObject3.put("name", "王五");
jsonObject3.put("age", 24);
jsonArray.add(jsonObject1);//三个对象添加到array中
jsonArray.add(jsonObject2);
jsonArray.add(jsonObject3);

resultJson.put("students", jsonArray);//把三个对象添加到数组中作为一个属性值放入resultJson中


out.println(resultJson);
out.flush();
out.close();
}

private void getJsonNested(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out=response.getWriter();
JSONObject resultJson=new JSONObject();
JSONArray jsonArray=new JSONArray();
JSONObject jsonObject1=new JSONObject();
jsonObject1.put("name", "张三");
jsonObject1.put("age", 22);

JSONObject scoreObject1=new JSONObject();
scoreObject1.put("chinese", 90);
scoreObject1.put("math", 100);
scoreObject1.put("english", 80);
jsonObject1.put("score", scoreObject1);

JSONObject jsonObject2=new JSONObject();
jsonObject2.put("name", "李四");
jsonObject2.put("age", 23);

JSONObject scoreObject2=new JSONObject();
scoreObject2.put("chinese", 70);
scoreObject2.put("math", 90);
scoreObject2.put("english", 90);
jsonObject2.put("score", scoreObject2);

JSONObject jsonObject3=new JSONObject();
jsonObject3.put("name", "王五");
jsonObject3.put("age", 24);

JSONObject scoreObject3=new JSONObject();
scoreObject3.put("chinese", 80);
scoreObject3.put("math", 60);
scoreObject3.put("english", 90);
jsonObject3.put("score", scoreObject3);

jsonArray.add(jsonObject1);
jsonArray.add(jsonObject2);
jsonArray.add(jsonObject3);

resultJson.put("students", jsonArray);
out.println(resultJson);
out.flush();
out.close();
}
}




JSON:JavaScript 对象表示法(JavaScript Object Notation)。
JSON 是存储和交换文本信息的语法。类似 XML。
JSON 比 XML 更小、更快,更易解析。
{
"employees": [
{ "firstName":"Bill" , "lastName":"Gates" },
{ "firstName":"George" , "lastName":"Bush" },
{ "firstName":"Thomas" , "lastName":"Carter" }
]
}
什么是 JSON ?
JSON 指的是 JavaScript 对象表示法(JavaScript Object Notation)
JSON 是轻量级的文本数据交换格式
JSON 独立于语言 *
JSON 具有自我描述性,更易理解
* JSON 使用 JavaScript 语法来描述数据对象,但是 JSON 仍然独立于语言和平台。JSON 解析器和 JSON 库支持许多不同的编程语言。
JSON - 转换为 JavaScript 对象
JSON 文本格式在语法上与创建 JavaScript 对象的代码相同。
由于这种相似性,无需解析器,JavaScript 程序能够使用内建的 eval() 函数,用 JSON 数据来生成原生的 JavaScript 对象。
通过我们的编辑器,您可以在线编辑 JavaScript 代码,然后通过点击一个按钮来查看结果:
<html>
<body>
<h2>在 JavaScript 中创建 JSON 对象</h2>


<p>
Name: <span id="jname"></span><br />
Age: <span id="jage"></span><br />
Address: <span id="jstreet"></span><br />
Phone: <span id="jphone"></span><br />
</p>


<script type="text/javascript">
var JSONObject= {
"name":"Bill Gates",
"street":"Fifth Avenue New York 666",
"age":56,
"phone":"555 1234567"};
document.getElementById("jname").innerHTML=JSONObject.name
document.getElementById("jage").innerHTML=JSONObject.age
document.getElementById("jstreet").innerHTML=JSONObject.street
document.getElementById("jphone").innerHTML=JSONObject.phone
</script>


</body>
</html>
类似 XML
JSON 是纯文本
JSON 具有“自我描述性”(人类可读)
JSON 具有层级结构(值中存在值)
JSON 可通过 JavaScript 进行解析
JSON 数据可使用 AJAX 进行传输
相比 XML 的不同之处
没有结束标签
更短
读写的速度更快
能够使用内建的 JavaScript eval() 方法进行解析
使用数组
不使用保留字


为什么使用 JSON?
对于 AJAX 应用程序来说,JSON 比 XML 更快更易使用:
使用 XML
读取 XML 文档
使用 XML DOM 来循环遍历文档
读取值并存储在变量中
使用 JSON
读取 JSON 字符串
用 eval() 处理 JSON 字符串
JSON 语法规则
JSON 语法是 JavaScript 对象表示法语法的子集。
数据在名称/值对中
数据由逗号分隔
花括号保存对象
方括号保存数组


JSON 名称/值对
JSON 数据的书写格式是:名称/值对。
名称/值对包括字段名称(在双引号中),后面写一个冒号,然后是值:
firstName" : "John"这很容易理解,等价于这条 JavaScript 语句:firstName = "John"
JSON 值
JSON 值可以是:
数字(整数或浮点数)
字符串(在双引号中)
逻辑值(true 或 false)
数组(在方括号中)
对象(在花括号中)
null
JSON 对象
JSON 对象在花括号中书写:
对象可以包含多个名称/值对:
{ "firstName":"John" , "lastName":"Doe" }
这一点也容易理解,与这条 JavaScript 语句等价:
firstName = "John"
lastName = "Doe"
JSON 数组
JSON 数组在方括号中书写:
数组可包含多个对象:
{
"employees": [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName":"Jones" }
]
}
在上面的例子中,对象 "employees" 是包含三个对象的数组。每个对象代表一条关于某人(有姓和名)的记录。
JSON 使用 JavaScript 语法
因为 JSON 使用 JavaScript 语法,所以无需额外的软件就能处理 JavaScript 中的 JSON。
通过 JavaScript,您可以创建一个对象数组,并像这样进行赋值:
var employees = [
{ "firstName":"Bill" , "lastName":"Gates" },
{ "firstName":"George" , "lastName":"Bush" },
{ "firstName":"Thomas" , "lastName": "Carter" }
];
employees[0].lastName;
可以像这样访问 JavaScript 对象数组中的第一项:
employees[0].lastName = "Jobs";
把 JSON 文本转换为 JavaScript 对象
JSON 最常见的用法之一,是从 web 服务器上读取 JSON 数据(作为文件或作为 HttpRequest),将 JSON 数据转换为 JavaScript 对象,然后在网页中使用该数据。
为了更简单地为您讲解,我们使用字符串作为输入进行演示(而不是文件)。
把 JSON 文本转换为 JavaScript 对象
JSON 最常见的用法之一,是从 web 服务器上读取 JSON 数据(作为文件或作为 HttpRequest),将 JSON 数据转换为 JavaScript 对象,然后在网页中使用该数据。
为了更简单地为您讲解,我们使用字符串作为输入进行演示(而不是文件)。
JSON 实例 - 来自字符串的对象
创建包含 JSON 语法的 JavaScript 字符串:
var txt = '{ "employees" : [' +
'{ "firstName":"Bill" , "lastName":"Gates" },' +
'{ "firstName":"George" , "lastName":"Bush" },' +
'{ "firstName":"Thomas" , "lastName":"Carter" } ]}';
由于 JSON 语法是 JavaScript 语法的子集,JavaScript 函数 eval() 可用于将 JSON 文本转换为 JavaScript 对象。
eval() 函数使用的是 JavaScript 编译器,可解析 JSON 文本,然后生成 JavaScript 对象。必须把文本包围在括号中,这样才能避免语法错误:
var obj = eval ("(" + txt + ")");
<p>
First Name: <span id="fname"></span><br />
Last Name: <span id="lname"></span><br />
</p>


<script type="text/javascript">
document.getElementById("fname").innerHTML = obj.employees[1].firstName
document.getElementById("lname").innerHTML = obj.employees[1].lastName
</script>
SON 解析器
提示:eval() 函数可编译并执行任何 JavaScript 代码。这隐藏了一个潜在的安全问题。
使用 JSON 解析器将 JSON 转换为 JavaScript 对象是更安全的做法。JSON 解析器只能识别 JSON 文本,而不会编译脚本。
在浏览器中,这提供了原生的 JSON 支持,而且 JSON 解析器的速度更快。
较新的浏览器和最新的 ECMAScript (JavaScript) 标准中均包含了原生的对 JSON 的支持。
       
       
       
Json交互

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
function checkUserName(){
var userName=document.getElementById("userName").value;
var xmlHttp;
if(window.XMLHttpRequest){
xmlHttp=new XMLHttpRequest();
}else{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState==4 && xmlHttp.status==200){
alert(xmlHttp.responseText);
var dataObj=eval("("+xmlHttp.responseText+")");
if(dataObj.exist){//true 给dom节点添加内容
document.getElementById("tip").innerHTML="<img src='no.png'/>&nbsp;该用户名已经存在";
}else{
document.getElementById("tip").innerHTML="<img src='ok.png'/>&nbsp;该用户名可用";
}
}
};
xmlHttp.open("get", "getAjaxInfo?action=checkUserName&userName="+userName, true);//获取的用户名跟在后面方法名换

    xmlHttp.send();
}
</script>
</head>
<body>
<table>
<tr>
<th>用户注册</th>
</tr>
<tr>
<td>用户名:</td>
<td><input type="text" id="userName" name="userName" onblur="checkUserName()"/>&nbsp;&nbsp;<font id="tip"></font></td>//失去焦点事件
</tr>
<tr>
<td>密码:</td>
<td><input type="text" id="password" name="password"/></td>
</tr>
<tr>
<td>确认密码:</td>
<td><input type="text" id="password2" name="password2"/></td>
</tr>
<tr>
<td><input type="submit" value="注册"/></td>
<td><input type="button" value="重置"/></td>
</tr>
</table>
</body>
</html>


<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<script type="text/javascript">
function loadInfo(){
var shengId=document.getElementById("sheng").value;
shi.options.length=0;  // 删除所有市下拉框的选项重置
var xmlHttp;
if(window.XMLHttpRequest){
xmlHttp=new XMLHttpRequest();
}else{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttp.onreadystatechange=function(){
if(xmlHttp.readyState==4 && xmlHttp.status==200){
alert(xmlHttp.responseText);
var dataObj=eval("("+xmlHttp.responseText+")");//转成json对象放到框里
for(var i=0;i<dataObj.rows.length;i++){//rows对象对应的值
var o=dataObj.rows[i];//取每一个对象市
shi.options.add(new Option(o.text,o.id));
}
}
};
xmlHttp.open("get", "getAjaxInfo?action=ejld&shengId="+shengId, true);//二级联动传到后台

    xmlHttp.send();
}
</script>
</head>
<body>
省:
<select id="sheng" onchange="loadInfo()">
<option value="1">江苏省</option>
<option value="2">山东省</option>
<option value="3">浙江省</option>
</select>
&nbsp;&nbsp;

<select id="shi">
</select>
</body>
</html>


package com.java1234.web;


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;


import net.sf.json.JSONArray;
import net.sf.json.JSONObject;


public class GetAjaxInfoServlet extends HttpServlet{


/**
 * 
 */
private static final long serialVersionUID = 1L;


@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}


@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
String action=request.getParameter("action");
if("checkUserName".equals(action)){
this.checkUserName(request, response);//后台
}else if("ejld".equals(action)){
this.ejld(request, response);
}

}



private void checkUserName(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out=response.getWriter();
String userName=request.getParameter("userName");
JSONObject resultJson=new JSONObject();
if("jack".equals(userName)){
resultJson.put("exist", true);//返回信息existboolean类型的
}else{
resultJson.put("exist", false);
}
out.println(resultJson);
out.flush();
out.close();
}

private void ejld(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out=response.getWriter();
String shengId=request.getParameter("shengId");//前台传过来的
JSONObject resultJson=new JSONObject();
JSONArray jsonArray=new JSONArray();//把获取的信息放到jsonarray中
JSONObject temp=null;//添加东西临时的东西
switch(Integer.parseInt(shengId)){
case 1:{
temp=new JSONObject();temp.put("id", 1);temp.put("text", "南京");jsonArray.add(temp);
temp=new JSONObject();temp.put("id", 2);temp.put("text", "南通");jsonArray.add(temp);
temp=new JSONObject();temp.put("id", 3);temp.put("text", "泰兴");jsonArray.add(temp);
break;
}
case 2:{
temp=new JSONObject();temp.put("id", 4);temp.put("text", "济南");jsonArray.add(temp);
temp=new JSONObject();temp.put("id", 5);temp.put("text", "烟台");jsonArray.add(temp);
temp=new JSONObject();temp.put("id", 6);temp.put("text", "蓬莱");jsonArray.add(temp);
break;
}
case 3:{
temp=new JSONObject();temp.put("id", 7);temp.put("text", "杭州");jsonArray.add(temp);
temp=new JSONObject();temp.put("id", 8);temp.put("text", "宁波");jsonArray.add(temp);
temp=new JSONObject();temp.put("id", 9);temp.put("text", "温州");jsonArray.add(temp);
break;
}
}
resultJson.put("rows", jsonArray);//把jsonarray添加到返回的json中
out.println(resultJson);//返回了一个json对象
out.flush();
out.close();
}

}




介绍:主要了解一下json的格式,看看数据是怎么存储的 
*/  
<p><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "<a target=_blank target="_blank" href="http://www.w3.org/TR/html4/loose.dtd">http://www.w3.org/TR/html4/loose.dtd</a>">  
<html>  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">  
<title>Insert title here</title>  
<script type="text/javascript">  
/* 
 class person 
 { 
  Integer id; 
  String name; 
 } 
 Person p=new Person(); 
*/  
 //jason格式标识一个对象  
 var people={"firstName":"zhangsan","lastName":"hao","email":"<a target=_blank target="_blank" href="mailto:1221@qq.com">1221@qq.com</a>"};  
 //alert(people.firstName);  
 //json标识多个人  
 var people2=  
 [  
  {"firstName":"zhangsan","lastName":"hao","email":"<a target=_blank target="_blank" href="mailto:1221@qq.com">1221@qq.com</a>"},  
  {"firstName":"zhangsan","lastName":"hao","email":"<a target=_blank target="_blank" href="mailto:1221@qq.com">1221@qq.com</a>"},  
  {"firstName":"zhangsan","lastName":"hao","email":"<a target=_blank target="_blank" href="mailto:1221@qq.com">1221@qq.com</a>"}  
 ]  
 //alert(people2[1].firstName);  
 //别名:  
 var people3={"person":  
 [  
  {"firstName":"zhangsan","lastName":"hao","email":"<a target=_blank target="_blank" href="mailto:1221@qq.com">1221@qq.com</a>"},  
  {"firstName":"zhangsan","lastName":"hao","email":"<a target=_blank target="_blank" href="mailto:1221@qq.com">1221@qq.com</a>"},  
  {"firstName":"zhangsan","lastName":"hao","email":"<a target=_blank target="_blank" href="mailto:1221@qq.com">1221@qq.com</a>"}  
 ]  
 }  
 //alert(people3.person[1].firstName);  
 var people3={  
 "person1":  
  [  
   {"firstName":"zhangsan","lastName":"hao","email":"<a target=_blank target="_blank" href="mailto:1221@qq.com">1221@qq.com</a>"},  
   {"firstName":"zhangsan","lastName":"hao","email":"<a target=_blank target="_blank" href="mailto:1221@qq.com">1221@qq.com</a>"},  
   {"firstName":"zhangsan","lastName":"hao","email":"<a target=_blank target="_blank" href="mailto:1221@qq.com">1221@qq.com</a>"}  
  ],  
 "person2":  
  [  
   {"firstName":"zhangsan","lastName":"hao","email":"<a target=_blank target="_blank" href="mailto:1221@qq.com">1221@qq.com</a>"},  
   {"firstName":"zhangsan","lastName":"hao","email":"<a target=_blank target="_blank" href="mailto:1221@qq.com">1221@qq.com</a>"},  
   {"firstName":"zhangsan","lastName":"hao","email":"<a target=_blank target="_blank" href="mailto:1221@qq.com">1221@qq.com</a>"}  
  ],  
 "person3":  
  [  
   {"firstName":"wy","lastName":"hao","email":"<a target=_blank target="_blank" href="mailto:1221@qq.com">1221@qq.com</a>"},  
   {"firstName":"zhangsan","lastName":"hao","email":"<a target=_blank target="_blank" href="mailto:1221@qq.com">1221@qq.com</a>"},  
   {"firstName":"zhangsan","lastName":"hao","email":"<a target=_blank target="_blank" href="mailto:1221@qq.com">1221@qq.com</a>"}  
  ]  
 }  
 //alert(people3.person3[0].firstName);  
   
</script>  
</head>  
<body></p><p></body>  
</html></p>       


绍:主要了学习一下json与后台交互的时候数据的转换 
*/  
<p><!DOCTYPE html>  
<html>  
  <head>  
    <title>json2.html</title>  
   
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
    <meta http-equiv="description" content="this is my page">  
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">  
      
    <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->  
 <script type="text/javascript">  
  function ajaxFunction()  
   {  
   var xmlHttp=null;  
     
   try  
      {  
     // Firefox, Opera 8.0+, Safari  
      xmlHttp=new XMLHttpRequest();  
      }  
   catch (e)  
      {</p><p>    // Internet Explorer  
     try  
        {  
        xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");  
        }  
     catch (e)  
        {</p><p>        try  
           {  
           xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");  
           }  
        catch (e)  
           {  
           alert("您的浏览器不支持AJAX!");  
           return false;  
           }  
        }  
      }  
   return xmlHttp;  
   }  
  window.onload=function()  
  {  
   document.getElementById("sub").onclick=function()  
   {  
    var xmlReq=ajaxFunction();  
    xmlReq.onreadystatechange=function()  
    {  
     if(xmlReq.readyState==4)  
     {  
      if(xmlReq.status==200||xmlReq.status==304)  
      {  
       var data=xmlReq.responseText;  
       //{pid:1,pname:'山东省'}  
       //alert(data);  
       var dataObj=eval("("+data+")");  
       //alert(dataObj);  
       //alert(dataObj.pname);  
       for(var i=0;i<dataObj.length;i++)  
       {  
        alert(dataObj[i].id+"  "+dataObj[i].addre);  
       }  
      }  
     }  
    }  
    xmlReq.open("post","../jsonServlet?timeStamp="+new Date().getTime(),true);  
    xmlReq.setRequestHeader("Content-Type","application/x-www-form-urlencoded");  
    //alert("adsada");  
    /* 
     * 3.发送数据 
     * */  
    xmlReq.send("b=0");  
   }  
  }  
 </script>  
  </head>  
    
  <body>  
    <input type="submit" value="提交" name="sub" id="sub"/>  
    <select id="province" name="province">  
     <option value="">请选择...</option>  
    </select>  
  </body>  
</html>  
</p>  
<p>package cn.com.Demo;</p><p>import java.io.IOException;  
import java.io.PrintWriter;  
import java.util.ArrayList;  
import java.util.List;</p><p>import javax.servlet.ServletException;  
import javax.servlet.http.HttpServlet;  
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;</p><p>import net.sf.json.JSONArray;  
import net.sf.json.JsonConfig;</p><p>import cn.com.bean.Province;</p><p>public class jsonServlet extends HttpServlet {</p><p>   
 public void doPost(HttpServletRequest request, HttpServletResponse response)  
   throws ServletException, IOException {  
  request.setCharacterEncoding("UTF-8");  
  response.setContentType("text/html; charset=utf-8");  
  PrintWriter out=response.getWriter();  
    
  System.out.println("---------------Post-----------------------");  
  System.out.println(request.getParameter("b"));  
  //out.write("你好!");  
  //一个省份的时候  
  //String str2="{pid:1,pname:'山东省'}";  
  //out.write(str2);  
    
    
  //多个省份的时候  
    
  //String str="[{pid:1,pname:'山东省'},{pid:2,pname:'四川'},{pid:3,pname:'北京'},{pid:4,pname:'上海'}]";  
  //out.write(str);  
    
  //  
  List<Province> list=new ArrayList<Province>();  
  Province p1=new Province(1,"山东");  
  Province p2=new Province(2,"北京");  
  Province p3=new Province(3,"上海");  
    
  list.add(p1);  
  list.add(p2);  
  list.add(p3);  
    
  JsonConfig config=new JsonConfig();  
  config.setExcludes(new String[]{"id"});  
  JSONArray jsonArray=JSONArray.fromObject(list,config);  
  out.write(jsonArray.toString());  
  System.out.println(jsonArray.toString());  
 }</p><p>}  
</p>  










































原创粉丝点击