이번에는 Json 및 XML 데이터의 Ajax 전송 단계(코드 포함)에 대해 자세히 설명합니다. Json 및 XML 데이터의 Ajax 전송 시 주의사항은 무엇인가요?
ajax는 xml 데이터를 전송합니다. 데이터가 xml 형식으로 캡슐화되어 있으면 전송이 실현될 수 있습니다. 프런트엔드 js는 xml 매개변수를 수신하기 위해 responseXML을 사용하고, 백그라운드 읽기에서는 스트림과 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나 Alibaba의 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()); } }마스터하셨을 거라 믿습니다. 이 기사의 사례를 읽은 후 더 흥미로운 정보를 보려면 PHP 중국어 웹사이트의 다른 관련 기사를 주목하세요! 추천 자료:
양식을 제출하고 ajax로 파일 업로드를 구현하는 방법
Ajax가 json 형식 데이터를 백그라운드로 전송할 때 오류를 처리하는 방법
위 내용은 Ajax를 통해 Json 및 XML 데이터를 전송하는 단계에 대한 자세한 설명(코드 포함)의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!