欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Ajax如何传输Json和xml数据

程序员文章站 2022-05-14 21:03:27
ajax传输xml数据:只要把数据封装成xml格式就可以实现传输,前台js用responsexml接收xml参数,后台读取用流和dom4j来解析 前台页面 &l...

ajax传输xml数据:只要把数据封装成xml格式就可以实现传输,前台js用responsexml接收xml参数,后台读取用流和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数据处理演示</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设置访问方式
   xhr.open("get", url, true);
   //4设置访问成功返回后的操作
   xhr.onreadystatechange=function(){
    if(xhr.readystate==4){//返回
     if(xhr.status==200){//响应代码正常
      var txt=xhr.responsetext;
      alert(txt);

     }
    }
   };
   xhr.send(null);
  }
 </script>

<!-- 前台以xml的格式向服务器发送数据 -->
<script type="text/javascript">
  //post方式ajax
  function send2(){
   alert("222");
   //1创建ajax对象
   var xhr = null;
   if(window.xmlhttprequest){//高版本
    xhr = new xmlhttprequest();
   }else{//低版本
    xhr = new activexobject("microsoft.xmlhttp");
   }

   //2请求地址
   var url = "<c:url value='/xmlservlet'/>";

   //3设置访问方式
   xhr.open("post", url, true);
   //4设置访问成功返回后的操作
   xhr.onreadystatechange=function(){
    if(xhr.readystate==4){//返回
     if(xhr.status==200){//响应代码正常
      var xmlobj=xhr.responsexml;
      var users=xmlobj.getelementsbytagname("user");
      for(var i=0;i<users.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数据处理演示</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设置访问方式
   xhr.open("get", url, true);
   //4设置访问成功返回后的操作
   xhr.onreadystatechange=function(){
    if(xhr.readystate==4){//返回
     if(xhr.status==200){//响应代码正常
      var txt=xhr.responsetext;
      alert(txt);

     }
    }
   };
   xhr.send(null);
  }
 </script>

<!-- 前台以xml的格式向服务器发送数据 -->
<script type="text/javascript">
  //post方式ajax
  function send2(){
   alert("222");
   //1创建ajax对象
   var xhr = null;
   if(window.xmlhttprequest){//高版本
    xhr = new xmlhttprequest();
   }else{//低版本
    xhr = new activexobject("microsoft.xmlhttp");
   }

   //2请求地址
   var url = "<c:url value='/xmlservlet'/>";

   //3设置访问方式
   xhr.open("post", url, true);
   //4设置访问成功返回后的操作
   xhr.onreadystatechange=function(){
    if(xhr.readystate==4){//返回
     if(xhr.status==200){//响应代码正常
      var xmlobj=xhr.responsexml;
      var users=xmlobj.getelementsbytagname("user");
      for(var i=0;i<users.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数据的要点利用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数据处理演示</title>
<script type="text/javascript">
 function ask1() {
  //1创建ajax对象
  var xhr = null;
  if (window.xmlhttprequest) {//高版本
   xhr = new xmlhttprequest();
  } else {//低版本
   xhr = new activexobject("microsoft.xmlhttp");
  }

  //2请求地址
  var url = "<c:url value='/jsonservlet1'/>";

  //3设置访问方式
  xhr.open("post", url, true);

  //4设置访问成功返回后的操作
  xhr.onreadystatechange = function() {
   if (xhr.readystate == 4) {//返回
    if (xhr.status == 200) {//响应代码正常
     //※※※※※解析后台返回的json串
     //js中eval()方法的功能:是校验参数文本串符合js中哪一种数据类型,并把其转换成对应类型的对象
     var txt = xhr.responsetext;
     var users = eval("(" + txt + ")"); //把符合json格式的文本串 转换成 json对象
     for ( var i = 0; i < users.length; i++) {
      alert(users[i].id + "," + users[i].name + ","
        + users[i].age);
     }
    }
   }
  };
  //5 发送
  xhr.send(null);
 }

 function ask2() {
  //1创建ajax对象
  var xhr = null;
  if (window.xmlhttprequest) {//高版本
   xhr = new xmlhttprequest();
  } else {//低版本
   xhr = new activexobject("microsoft.xmlhttp");
  }

  //2请求地址
  var url = "<c:url value='/jsonservlet2'/>";

  //3设置访问方式
  xhr.open("post", url, true);

  //4设置访问成功返回后的操作
  xhr.onreadystatechange = function() {
   if (xhr.readystate == 4) {//返回
    if (xhr.status == 200) {//响应代码正常
     //※※※※※解析后台返回的json串
     //js中eval()方法的功能:是校验参数文本串符合js中哪一种数据类型,并把其转换成对应类型的对象
     var txt = xhr.responsetext;
     //alert(txt);
     //把符合json格式的文本串 转换成 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 发送
  xhr.send(null);
 }


 function ask3() {
  //1创建ajax对象
  var xhr = null;
  if (window.xmlhttprequest) {//高版本
   xhr = new xmlhttprequest();
  } else {//低版本
   xhr = new activexobject("microsoft.xmlhttp");
  }

  //2请求地址
  var url = "<c:url value='/jsonservlet2'/>";

  //3设置访问方式
  xhr.open("post", url, true);

  //4设置访问成功返回后的操作
  xhr.onreadystatechange = function() {
   if (xhr.readystate == 4) {//返回
    if (xhr.status == 200) {//响应代码正常
     //※※※※※解析后台返回的json串
     //js中eval()方法的功能:是校验参数文本串符合js中哪一种数据类型,并把其转换成对应类型的对象
     var txt = xhr.responsetext;
     //alert(txt);
     //把符合json格式的文本串 转换成 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 发送
  xhr.send(null);
 }
</script>

</head>
<body>
 <input type="button" onclick="ask1();" value="ajax请求后台数据(手动封装json方式)" />
 <br />
 <input type="button" onclick="ask2();"
  value="ajax请求后台数据(用apache工具封装json方式)" />
 <input type="button" onclick="ask3()" value="ajax请求后台数据(用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 {
  //调用后台service.dao.query(),到数据库当中把信息读取出来
  //为简化知识点的理解,此处后台部分的功能直接模拟
  response.setcontenttype("text/html;charset=utf-8");
  printwriter out = response.getwriter();
  list<user> users = new arraylist<user>();
  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();
  list<user> users = new arraylist<user>();
  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转换成json串
  map<string, object> map = new hashmap<string, 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();
  list<user> users = new arraylist<user>();
  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转换成json串
  jsonarray json=jsonarray.fromobject(users);
  string strjson=json.tostring();
  system.out.println(strjson);

  map<string, object> map = new hashmap<string, 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());
 }

}


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。