


Detailed explanation of the steps to transmit Json and XML data via Ajax (with code)
This time I will bring you a detailed explanation of the steps for Ajax transmission of Json and XML data (with code). What are the precautions for Ajax transmission of Json and XML data? The following is a practical case, let’s take a look .
ajax transmits xml data: As long as the data is encapsulated into xml format, the transmission can be achieved. The front-end js uses responseXML to receive xml parameters, and the background reading uses streams and dom4j to parse
Front 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='/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>
Backend 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='/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>
-------------------------------- --------------------------------------------------
The key 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='/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()); } }
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!
Recommended reading:
How does ajax submit a form and implement file upload
Ajax transmits json format data to the background. How to handle errors
The above is the detailed content of Detailed explanation of the steps to transmit Json and XML data via Ajax (with code). For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Performance optimization methods for converting PHP arrays to JSON include: using JSON extensions and the json_encode() function; adding the JSON_UNESCAPED_UNICODE option to avoid character escaping; using buffers to improve loop encoding performance; caching JSON encoding results; and considering using a third-party JSON encoding library.

Annotations in the Jackson library control JSON serialization and deserialization: Serialization: @JsonIgnore: Ignore the property @JsonProperty: Specify the name @JsonGetter: Use the get method @JsonSetter: Use the set method Deserialization: @JsonIgnoreProperties: Ignore the property @ JsonProperty: Specify name @JsonCreator: Use constructor @JsonDeserialize: Custom logic

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

In-depth understanding of PHP: Implementation method of converting JSONUnicode to Chinese During development, we often encounter situations where we need to process JSON data, and Unicode encoding in JSON will cause us some problems in some scenarios, especially when Unicode needs to be converted When encoding is converted to Chinese characters. In PHP, there are some methods that can help us achieve this conversion process. A common method will be introduced below and specific code examples will be provided. First, let us first understand the Un in JSON

Ajax (Asynchronous JavaScript and XML) allows adding dynamic content without reloading the page. Using PHP and Ajax, you can dynamically load a product list: HTML creates a page with a container element, and the Ajax request adds the data to that element after loading it. JavaScript uses Ajax to send a request to the server through XMLHttpRequest to obtain product data in JSON format from the server. PHP uses MySQL to query product data from the database and encode it into JSON format. JavaScript parses the JSON data and displays it in the page container. Clicking the button triggers an Ajax request to load the product list.

JSON (JavaScriptObjectNotation) is a lightweight data exchange format commonly used for data exchange between web applications. When processing JSON data, we often encounter Unicode-encoded Chinese characters (such as "u4e2du6587") and need to convert them into readable Chinese characters. In PHP, we can achieve this conversion through some simple methods. Next, we will detail how to convert JSONUnico

PHP arrays can be converted to JSON strings through the json_encode() function (for example: $json=json_encode($array);), and conversely, the json_decode() function can be used to convert from JSON to arrays ($array=json_decode($json);) . Other tips include avoiding deep conversions, specifying custom options, and using third-party libraries.
