ajax傳輸xml數(shù)據(jù):只要把數(shù)據(jù)封裝成xml格式就可以實現(xiàn)傳輸,前臺js用responseXML接收xml參數(shù),后臺讀取用流和dom4j來解析
前臺頁面
%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
html>
head>
title>Ajax XML數(shù)據(jù)處理演示/title>
script type="text/javascript">
//get方式ajax
function send1(){
alert("ok");
var name=document.getElementsByName("name")[0].value;
var age=document.getElementsByName("age")[0].value;
var xhr=null;
if(window.XMLHttpRequest){
xhr=new XMLHttpRequest();
}else{
xhr=new ActiveXObject("Microsoft.XMLHttp");
}
var url="c:url value='/XmlServlet?name='/>"+name+"age="+age;
//3設(shè)置訪問方式
xhr.open("GET", url, true);
//4設(shè)置訪問成功返回后的操作
xhr.onreadystatechange=function(){
if(xhr.readyState==4){//返回
if(xhr.status==200){//響應(yīng)代碼正常
var txt=xhr.responseText;
alert(txt);
}
}
};
xhr.send(null);
}
/script>
!-- 前臺以xml的格式向服務(wù)器發(fā)送數(shù)據(jù) -->
script type="text/javascript">
//post方式ajax
function send2(){
alert("222");
//1創(chuàng)建ajax對象
var xhr = null;
if(window.XMLHttpRequest){//高版本
xhr = new XMLHttpRequest();
}else{//低版本
xhr = new ActiveXObject("Microsoft.XMLHttp");
}
//2請求地址
var url = "c:url value='/XmlServlet'/>";
//3設(shè)置訪問方式
xhr.open("POST", url, true);
//4設(shè)置訪問成功返回后的操作
xhr.onreadystatechange=function(){
if(xhr.readyState==4){//返回
if(xhr.status==200){//響應(yīng)代碼正常
var xmlObj=xhr.responseXML;
var users=xmlObj.getElementsByTagName("user");
for(var i=0;iusers.length;i++){
var id=users[i].getAttribute("id");
var name=users[i].childNodes[0].firstChild.data;//xml中的dom模型中的操作方法,和html中有點小差別
var age=users[i].childNodes[1].firstChild.data;//不能用childNodes["age"]
alert(id+","+name+","+age);
}
}
}
};
var name=document.getElementsByName("name")[0].value;
var age=document.getElementsByName("age")[0].value;
var xml="user>name>"+name+"/name>age>"+age+"/age>/user>";
xhr.send(xml);
}
/script>
/head>
body>
Name:
input type="text" name="name">
br /> Age:
input type="text" name="age">
br />
input type="button" value="Get提交" onclick="send1();" />
br />
input type="button" value="Post提交" onclick="send2()" />
br />
/body>
/html>
后臺頁面
%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
html>
head>
title>Ajax XML數(shù)據(jù)處理演示/title>
script type="text/javascript">
//get方式ajax
function send1(){
alert("ok");
var name=document.getElementsByName("name")[0].value;
var age=document.getElementsByName("age")[0].value;
var xhr=null;
if(window.XMLHttpRequest){
xhr=new XMLHttpRequest();
}else{
xhr=new ActiveXObject("Microsoft.XMLHttp");
}
var url="c:url value='/XmlServlet?name='/>"+name+"age="+age;
//3設(shè)置訪問方式
xhr.open("GET", url, true);
//4設(shè)置訪問成功返回后的操作
xhr.onreadystatechange=function(){
if(xhr.readyState==4){//返回
if(xhr.status==200){//響應(yīng)代碼正常
var txt=xhr.responseText;
alert(txt);
}
}
};
xhr.send(null);
}
/script>
!-- 前臺以xml的格式向服務(wù)器發(fā)送數(shù)據(jù) -->
script type="text/javascript">
//post方式ajax
function send2(){
alert("222");
//1創(chuàng)建ajax對象
var xhr = null;
if(window.XMLHttpRequest){//高版本
xhr = new XMLHttpRequest();
}else{//低版本
xhr = new ActiveXObject("Microsoft.XMLHttp");
}
//2請求地址
var url = "c:url value='/XmlServlet'/>";
//3設(shè)置訪問方式
xhr.open("POST", url, true);
//4設(shè)置訪問成功返回后的操作
xhr.onreadystatechange=function(){
if(xhr.readyState==4){//返回
if(xhr.status==200){//響應(yīng)代碼正常
var xmlObj=xhr.responseXML;
var users=xmlObj.getElementsByTagName("user");
for(var i=0;iusers.length;i++){
var id=users[i].getAttribute("id");
var name=users[i].childNodes[0].firstChild.data;//xml中的dom模型中的操作方法,和html中有點小差別
var age=users[i].childNodes[1].firstChild.data;//不能用childNodes["age"]
alert(id+","+name+","+age);
}
}
}
};
var name=document.getElementsByName("name")[0].value;
var age=document.getElementsByName("age")[0].value;
var xml="user>name>"+name+"/name>age>"+age+"/age>/user>";
xhr.send(xml);
}
/script>
/head>
body>
Name:
input type="text" name="name">
br /> Age:
input type="text" name="age">
br />
input type="button" value="Get提交" onclick="send1();" />
br />
input type="button" value="Post提交" onclick="send2()" />
br />
/body>
/html>
--------------------------------------------------------------------------------
Ajax傳輸Json數(shù)據(jù)的要點利用Apache或者阿里巴巴的JSONArray類進行傳輸
前臺代碼
%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
html>
head>
title>Ajax Json數(shù)據(jù)處理演示/title>
script type="text/javascript">
function ask1() {
//1創(chuàng)建ajax對象
var xhr = null;
if (window.XMLHttpRequest) {//高版本
xhr = new XMLHttpRequest();
} else {//低版本
xhr = new ActiveXObject("Microsoft.XMLHttp");
}
//2請求地址
var url = "c:url value='/JsonServlet1'/>";
//3設(shè)置訪問方式
xhr.open("POST", url, true);
//4設(shè)置訪問成功返回后的操作
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {//返回
if (xhr.status == 200) {//響應(yīng)代碼正常
//※※※※※解析后臺返回的json串
//js中eval()方法的功能:是校驗參數(shù)文本串符合js中哪一種數(shù)據(jù)類型,并把其轉(zhuǎn)換成對應(yīng)類型的對象
var txt = xhr.responseText;
var users = eval("(" + txt + ")"); //把符合json格式的文本串 轉(zhuǎn)換成 json對象
for ( var i = 0; i users.length; i++) {
alert(users[i].id + "," + users[i].name + ","
+ users[i].age);
}
}
}
};
//5 發(fā)送
xhr.send(null);
}
function ask2() {
//1創(chuàng)建ajax對象
var xhr = null;
if (window.XMLHttpRequest) {//高版本
xhr = new XMLHttpRequest();
} else {//低版本
xhr = new ActiveXObject("Microsoft.XMLHttp");
}
//2請求地址
var url = "c:url value='/JsonServlet2'/>";
//3設(shè)置訪問方式
xhr.open("POST", url, true);
//4設(shè)置訪問成功返回后的操作
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {//返回
if (xhr.status == 200) {//響應(yīng)代碼正常
//※※※※※解析后臺返回的json串
//js中eval()方法的功能:是校驗參數(shù)文本串符合js中哪一種數(shù)據(jù)類型,并把其轉(zhuǎn)換成對應(yīng)類型的對象
var txt = xhr.responseText;
//alert(txt);
//把符合json格式的文本串 轉(zhuǎn)換成 json對象
var users = eval("(" + txt + ")");
for ( var key in users)//map的便利方式
alert("屬性:" + key + ",值:" + users[key]);
}
//for ( var i = 0; i users.length; i++) {//list的遍歷方式
//alert(users[i].id +","+users[i].name+","+users[i].age);
//}
};
};
//5 發(fā)送
xhr.send(null);
}
function ask3() {
//1創(chuàng)建ajax對象
var xhr = null;
if (window.XMLHttpRequest) {//高版本
xhr = new XMLHttpRequest();
} else {//低版本
xhr = new ActiveXObject("Microsoft.XMLHttp");
}
//2請求地址
var url = "c:url value='/JsonServlet2'/>";
//3設(shè)置訪問方式
xhr.open("POST", url, true);
//4設(shè)置訪問成功返回后的操作
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {//返回
if (xhr.status == 200) {//響應(yīng)代碼正常
//※※※※※解析后臺返回的json串
//js中eval()方法的功能:是校驗參數(shù)文本串符合js中哪一種數(shù)據(jù)類型,并把其轉(zhuǎn)換成對應(yīng)類型的對象
var txt = xhr.responseText;
//alert(txt);
//把符合json格式的文本串 轉(zhuǎn)換成 json對象
var users = eval("(" + txt + ")");
for ( var key in users)//map的便利方式
alert("屬性:" + key + ",值:" + users[key]);
}
//for ( var i = 0; i users.length; i++) {//list的遍歷方式
//alert(users[i].id +","+users[i].name+","+users[i].age);
//}
};
};
//5 發(fā)送
xhr.send(null);
}
/script>
/head>
body>
input type="button" onclick="ask1();" value="ajax請求后臺數(shù)據(jù)(手動封裝json方式)" />
br />
input type="button" onclick="ask2();"
value="ajax請求后臺數(shù)據(jù)(用apache工具封裝json方式)" />
input type="button" onclick="ask3()" value="ajax請求后臺數(shù)據(jù)(用fastjson工具封裝json方式)" />
/body>
/html>
JsonServlet1.java
package cn.hncu.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.hncu.domain.User;
public class JsonServlet1 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//調(diào)用后臺service.dao.query(),到數(shù)據(jù)庫當(dāng)中把信息讀取出來
//為簡化知識點的理解,此處后臺部分的功能直接模擬
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
ListUser> users = new ArrayListUser>();
users.add(new User("A001","Jack",20));
users.add(new User("A002","Rose",22));
users.add(new User("B001","張三",20));
users.add(new User("B002","李四",30));
String json="";
//用java封裝出json格式的字符串:[{name:"Jack",age:25}, {...}, {...} ]
for(User u:users){
if(json.equals("")){
json="{name:\""+u.getName()+"\",id:\""+u.getId()+"\",age:"+u.getAge()+"}";
}else{
json = json +",{ name:\""+u.getName()+"\",id:\""+u.getId()+"\",age:"+u.getAge()+"}" ;
}
}
json="["+json+"]";
out.print(json);
}
}
JsonServlet2.java
package cn.hncu.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import cn.hncu.domain.User;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class JsonServlet2 extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
ListUser> users = new ArrayListUser>();
users.add(new User("A001","Jack",20));
users.add(new User("A002","Rose",22));
users.add(new User("B001","張三",20));
users.add(new User("B002","李四",30));
String strJson=com.alibaba.fastjson.JSONArray.toJSONString(users);
System.out.println(strJson);
//用fastjson工具(只有一個jar包)幫我們把list轉(zhuǎn)換成json串
MapString, Object> map = new HashMapString, Object>();
map.put("addr", "湖南");
map.put("height", "170");
map.put("marry", "no");
map.put("user", new User("A003","小李",25));
String strMap=com.alibaba.fastjson.JSONArray.toJSONString(map);
out.print(strMap.toString());
}
}
JsonServlet3.java
package cn.hncu.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
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;
import cn.hncu.domain.User;
public class JsonServlet3 extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
PrintWriter out = response.getWriter();
ListUser> users = new ArrayListUser>();
users.add(new User("A001","Jack",20));
users.add(new User("A002","Rose",22));
users.add(new User("B001","張三",20));
users.add(new User("B002","李四",30));
//用fastjson工具(只有一個jar包)幫我們把list轉(zhuǎn)換成json串
JSONArray json=JSONArray.fromObject(users);
String strJson=json.toString();
System.out.println(strJson);
MapString, Object> map = new HashMapString, Object>();
map.put("addr", "湖南");
map.put("height", "170");
map.put("marry", "no");
map.put("user", new User("A003","小李",25));
JSONObject obj = JSONObject.fromObject(map);
System.out.println(obj.toString());
out.print(obj.toString());
}
}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
您可能感興趣的文章:- $.ajax json數(shù)據(jù)傳遞方法
- jQuery Ajax異步處理Json數(shù)據(jù)詳解
- jquery的ajax異步請求接收返回json數(shù)據(jù)實例
- 淺析ajax請求json數(shù)據(jù)并用js解析(示例分析)
- jquery的ajax和getJson跨域獲取json數(shù)據(jù)的實現(xiàn)方法
- jQuery中使用Ajax獲取JSON格式數(shù)據(jù)示例代碼
- 詳談 Jquery Ajax異步處理Json數(shù)據(jù).
- jquery序列化form表單使用ajax提交后處理返回的json數(shù)據(jù)
- AJAX如何接收JSON數(shù)據(jù)示例介紹
- ajax用json實現(xiàn)數(shù)據(jù)傳輸