English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

How Ajax Transmits Json and Xml Data

ajax to transmit XML data:just encapsulate the data into XML format to achieve transmission, the front-end JS uses responseXML to receive XML parameters, and the background reads using streams and DOM4j to parse

front-end page

<%@ 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 Data Processing Demonstration</title>
<script type="text/javascript">
  //ajax in get format
  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;
   //3set the access method
   xhr.open("GET", url, true);
   //4set the operation after the access is successful
   xhr.onreadystatechange=function(){
    if(xhr.readyState==4{//return
     if(xhr.status==200){//Response code is normal
      var txt=xhr.responseText;
      alert(txt);
     }
    }
   };
   xhr.send(null);
  }
 </script>
!-- the front-end sends data to the server in XML format -->
<script type="text/javascript">
  //ajax in post format
  function send2(){
   alert("222");
   //1create an AJAX object
   var xhr = null;
   if(window.XMLHttpRequest){//for high version
    xhr = new XMLHttpRequest();
   }else{//for low version
    xhr = new ActiveXObject("Microsoft.XMLHttp");
   }
   //2request address
   var url = "<c:url value='/XmlServlet'/>";
   //3set the access method
   xhr.open("POST", url, true);
   //4set the operation after the access is successful
   xhr.onreadystatechange=function(){
    if(xhr.readyState==4{//return
     if(xhr.status==200){//Response code is normal
      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;//the operation methods in the DOM model of XML are slightly different from those in HTML
       var age=users[i].childNodes[1].firstChild.data;//cannot use 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 Submit" onclick="send1();" />
 <br />
 <input type="button" value="Post Submit" onclick="send2()" />
 <br />
</body>
</html>

background page

<%@ 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 Data Processing Demonstration</title>
<script type="text/javascript">
  //ajax in get format
  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;
   //3set the access method
   xhr.open("GET", url, true);
   //4set the operation after the access is successful
   xhr.onreadystatechange=function(){
    if(xhr.readyState==4{//return
     if(xhr.status==200){//Response code is normal
      var txt=xhr.responseText;
      alert(txt);
     }
    }
   };
   xhr.send(null);
  }
 </script>
!-- the front-end sends data to the server in XML format -->
<script type="text/javascript">
  //ajax in post format
  function send2(){
   alert("222");
   //1create an AJAX object
   var xhr = null;
   if(window.XMLHttpRequest){//for high version
    xhr = new XMLHttpRequest();
   }else{//for low version
    xhr = new ActiveXObject("Microsoft.XMLHttp");
   }
   //2request address
   var url = "<c:url value='/XmlServlet'/>";
   //3set the access method
   xhr.open("POST", url, true);
   //4set the operation after the access is successful
   xhr.onreadystatechange=function(){
    if(xhr.readyState==4{//return
     if(xhr.status==200){//Response code is normal
      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;//the operation methods in the DOM model of XML are slightly different from those in HTML
       var age=users[i].childNodes[1].firstChild.data;//cannot use 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 Submit" onclick="send1();" />
 <br />
 <input type="button" value="Post Submit" onclick="send2()" />
 <br />
</body>
</html>

--------------------------------------------------------------------------------

Ajax transmits Json datauses Apache or Alibaba's JSONArray class for transmission
front-end code

<%@ 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 Data Processing Demonstration</title>
<script type="text/javascript">
 function ask1() {
  //1create an AJAX object
  var xhr = null;
  if (window.XMLHttpRequest) {//for high version
   xhr = new XMLHttpRequest();
  } else {//for low version
   xhr = new ActiveXObject("Microsoft.XMLHttp");
  }
  //2request address
  var url = "<c:url value='/JsonServlet1'/>";
  //3set the access method
  xhr.open("POST", url, true);
  //4set the operation after the access is successful
  xhr.onreadystatechange = function() {
   if (xhr.readyState === 4) {//return
    if (xhr.status === 200) {}}//Response code is normal
     //※※※※※Parse the returned JSON string from the background
     //The function of the js eval() method: It is to check which data type the parameter text string conforms to in js, and convert it into the corresponding type of object
     var txt = xhr.responseText;
     var users = eval("(" + txt + ")"); //Convert the text string that conforms to JSON format into a JSON object
     for ( var i = 0; i < users.length; i++) {
      alert(users[i].id + "," + users[i].name + ","
        + users[i].age);
     }
    }
   }
  };
  //5 Send
  xhr.send(null);
 }
 function ask2() {
  //1create an AJAX object
  var xhr = null;
  if (window.XMLHttpRequest) {//for high version
   xhr = new XMLHttpRequest();
  } else {//for low version
   xhr = new ActiveXObject("Microsoft.XMLHttp");
  }
  //2request address
  var url = "<c:url value='/JsonServlet2'/>";
  //3set the access method
  xhr.open("POST", url, true);
  //4set the operation after the access is successful
  xhr.onreadystatechange = function() {
   if (xhr.readyState === 4) {//return
    if (xhr.status === 200) {}}//Response code is normal
     //※※※※※Parse the returned JSON string from the background
     //The function of the js eval() method: It is to check which data type the parameter text string conforms to in js, and convert it into the corresponding type of object
     var txt = xhr.responseText;
     //alert(txt);
     //Convert the text string that conforms to JSON format into a JSON object
     var users = eval("(" + txt + ")"); 
     for ( var key in users)//map traversal method
      alert("Property:" + key + ",value:" + users[key]);
     }
     //for ( var i = 0; i < users.length; i++) {//list traversal method
      //alert(users[i].id +","+users[i].name+","+users[i].age);
     //}
   };
  };
  //5 Send
  xhr.send(null);
 }
 function ask3() {
  //1create an AJAX object
  var xhr = null;
  if (window.XMLHttpRequest) {//for high version
   xhr = new XMLHttpRequest();
  } else {//for low version
   xhr = new ActiveXObject("Microsoft.XMLHttp");
  }
  //2request address
  var url = "<c:url value='/JsonServlet2'/>";
  //3set the access method
  xhr.open("POST", url, true);
  //4set the operation after the access is successful
  xhr.onreadystatechange = function() {
   if (xhr.readyState === 4) {//return
    if (xhr.status === 200) {}}//Response code is normal
     //※※※※※Parse the returned JSON string from the background
     //The function of the js eval() method: It is to check which data type the parameter text string conforms to in js, and convert it into the corresponding type of object
     var txt = xhr.responseText;
     //alert(txt);
     //Convert the text string that conforms to JSON format into a JSON object
     var users = eval("(" + txt + ")"); 
     for ( var key in users)//map traversal method
      alert("Property:" + key + ",value:" + users[key]);
     }
     //for ( var i = 0; i < users.length; i++) {//list traversal method
      //alert(users[i].id +","+users[i].name+","+users[i].age);
     //}
   };
  };
  //5 Send
  xhr.send(null);
 }
</script>
</head>
<body>
 <input type="button" onclick="ask1();" value="ajax request background data (manual JSON encapsulation)" />
 <br />
 <input type="button" onclick="ask2();"
  value="ajax request background data (using apache tool to encapsulate JSON format)" />
 <input type="button" onclick="ask3()" value="ajax request background data (using fastjson tool to encapsulate JSON format)" />
</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 {
  //Call the background service.dao.query() to read the information from the database
  //For the sake of simplifying the understanding of knowledge points, the background part of the function is directly simulated
  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","Zhang San",20));
  users.add(new User("B002","Li Si",30));
  String json="";
  //Use Java to encapsulate a JSON formatted string: [{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","Zhang San",20));
  users.add(new User("B002","Li Si",30));
  String strJson=com.alibaba.fastjson.JSONArray.toJSONString(users);
  System.out.println(strJson);
  //Use the fastjson tool (only one jar package) to convert the list to a JSON string
  Map<String, Object> map = new HashMap<String, Object>();
  map.put("addr", "Hunan");
  map.put("height", "170");
  map.put("marry", "no");
  map.put("user", new User("A003","Little Li",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","Zhang San",20));
  users.add(new User("B002","Li Si",30));
  //Use the fastjson tool (only one jar package) to convert the list to a JSON string
  JSONArray json=JSONArray.fromObject(users);
  String strJson=json.toString();
  System.out.println(strJson);
  Map<String, Object> map = new HashMap<String, Object>();
  map.put("addr", "Hunan");
  map.put("height", "170");
  map.put("marry", "no");
  map.put("user", new User("A003","Little Li",25));
  JSONObject obj = JSONObject.fromObject(map);
  System.out.println(obj.toString());
  out.print(obj.toString());
 }
}

That's all for this article. Hope it will be helpful to your learning and also hope everyone will support the Yelling Tutorial more.

Statement: The content of this article is from the Internet, the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any content suspected of copyright infringement, please send an email to: notice#w3Please report via email to codebox.com (replace # with @) and provide relevant evidence. Once verified, this site will immediately delete the infringing content.