search
HomeWeb Front-endJS TutorialHow Ajax transmits Json and xml data

How Ajax transmits Json and xml data

Dec 30, 2017 pm 08:15 PM
ajaxjavascriptjson

This article mainly introduces in detail how Ajax transmits Json and xml data. It has certain reference value for learning ajax. How to Ajax Friends who are interested in or unfamiliar with transmitting Json and xml data can refer to

ajax transmission of xml data: As long as the data is encapsulated into xml format, the transmission can be achieved, and the front-end js is used responseXML receives xml parameters, and background reading uses streams and dom4j to parse

Foreground 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数据处理演示</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=&#39;/XmlServlet?name=&#39;/>"+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=&#39;/XmlServlet&#39;/>";

   //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>


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数据处理演示</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=&#39;/XmlServlet?name=&#39;/>"+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=&#39;/XmlServlet&#39;/>";

   //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>


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

The main points of Ajax transmission of Json dataUse 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数据处理演示</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=&#39;/JsonServlet1&#39;/>";

  //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=&#39;/JsonServlet2&#39;/>";

  //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=&#39;/JsonServlet2&#39;/>";

  //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());
 }

}


The above is the summary of this article All the content, I hope it will be helpful to everyone's learning, and I also hope everyone will support the PHP Chinese website.


Related recommendations:

Detailed explanation of the example of Ajax passing array parameter value to the server

Example analysis of the method of asynchronously submitting form data in jquery ajax

Sharing the strength of Ajax in realizing dynamic loading of data

The above is the detailed content of How Ajax transmits Json and xml data. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

The Origins of JavaScript: Exploring Its Implementation LanguageThe Origins of JavaScript: Exploring Its Implementation LanguageApr 29, 2025 am 12:51 AM

JavaScript originated in 1995 and was created by Brandon Ike, and realized the language into C. 1.C language provides high performance and system-level programming capabilities for JavaScript. 2. JavaScript's memory management and performance optimization rely on C language. 3. The cross-platform feature of C language helps JavaScript run efficiently on different operating systems.

Behind the Scenes: What Language Powers JavaScript?Behind the Scenes: What Language Powers JavaScript?Apr 28, 2025 am 12:01 AM

JavaScript runs in browsers and Node.js environments and relies on the JavaScript engine to parse and execute code. 1) Generate abstract syntax tree (AST) in the parsing stage; 2) convert AST into bytecode or machine code in the compilation stage; 3) execute the compiled code in the execution stage.

The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),