ajax 三种数据格式
生活随笔
收集整理的這篇文章主要介紹了
ajax 三种数据格式
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1.JSON(格式要正確,可以引jar包操作)
servlet代碼
1 package com.hsp.action; 2 3 import java.io.IOException; 4 import java.io.PrintWriter; 5 6 import javax.json.JsonString; 7 import javax.servlet.ServletException; 8 import javax.servlet.annotation.WebServlet; 9 import javax.servlet.http.HttpServlet; 10 import javax.servlet.http.HttpServletRequest; 11 import javax.servlet.http.HttpServletResponse; 12 13 /** 14 * Servlet implementation class showCities 15 */ 16 @WebServlet("/showCities") 17 public class showCities extends HttpServlet { 18 private static final long serialVersionUID = 1L; 19 20 /** 21 * @see HttpServlet#HttpServlet() 22 */ 23 public showCities() { 24 super(); 25 // TODO Auto-generated constructor stub 26 } 27 28 /** 29 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 30 */ 31 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 32 // TODO Auto-generated method stub 33 } 34 35 /** 36 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 37 */ 38 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 39 // TODO Auto-generated method stub 40 response.setContentType("text/xml;charset=utf-8"); 41 response.setHeader("Cache-Control", "no-cache"); 42 43 //接收用戶選擇的省的名字 44 String shengString=request.getParameter("province"); 45 System.out.println(shengString); 46 PrintWriter out=response.getWriter(); 47 StringBuilder builder=new StringBuilder(); 48 49 50 String info=""; 51 52 // if ("zhejiang".equals(shengString)) { 53 // System.out.println("浙江"); 54 // info="<province><city>杭州</city><city>溫州</city><city>寧波</city></province>"; 55 // } 56 // else if ("jiangsu".equals(shengString)) { 57 // System.out.println("江蘇"); 58 // 59 // info="<province><city>南京</city><city>徐州</city><city>蘇州</city></province>"; 60 // } 61 if ("zhejiang".equals(shengString)) 62 { 63 info= "[{"+'"'+"city"+'"'+":"+'"'+"杭州"+'"'+"},{"+'"'+"city"+'"'+":"+'"'+"溫州"+'"'+"}]"; 64 } 65 else if ("jiangsu".equals(shengString)) { 66 info= "[{"+'"'+"city"+'"'+":"+'"'+"南京"+'"'+"},{"+'"'+"city"+'"'+":"+'"'+"蘇州"+'"'+"}]"; 67 68 } 69 System.out.println("{"+'"'+"ins"+'"'+":"+info+"}"); 70 builder.append("{"+'"'+"ins"+'"'+":"+info+"}"); 71 72 out.println(builder.toString()); 73 } 74 75 }jsp代碼
1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 <% 3 String path = request.getContextPath(); 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 5 %> 6 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 8 <html> 9 <head> 10 <base href="<%=basePath%>"> 11 12 <title>My JSP 'Mycity.jsp' starting page</title> 13 14 <meta http-equiv="pragma" content="no-cache"> 15 <meta http-equiv="cache-control" content="no-cache"> 16 <meta http-equiv="expires" content="0"> 17 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 18 <meta http-equiv="description" content="This is my page"> 19 <!-- 20 <link rel="stylesheet" type="text/css" href="styles.css"> 21 --> 22 23 </head> 24 25 <body> 26 <script type="text/javascript"> 27 //1.創建ajax引擎 28 function getXmlHttpObject(){ 29 var xmlHttpRequest; 30 //不同的瀏覽器獲取對象xmlhttprequest對象方法不一樣 31 if(window.ActiveXobject) 32 { 33 xmlHttpRequest=new ActiveXobject("Microsoft.XMLHTTP"); 34 } 35 else 36 { 37 xmlHttpRequest=new XMLHttpRequest(); 38 } 39 return xmlHttpRequest; 40 } 41 42 //新建myXmlHttpRequest對象 43 var myXmlHttpRequest=""; 44 45 function getCities(){ 46 //創建對象 47 myXmlHttpRequest=getXmlHttpObject(); 48 // window.alert(myXmlHttpRequest); 49 //如果創建成功,則進行post請求 50 if(myXmlHttpRequest){ 51 //創建url 52 var url="/ajax/showCities";//post 53 //攜帶的參數 54 var data="province="+$('sheng').value; 55 // 56 myXmlHttpRequest.open("post",url,true); 57 //必填 58 myXmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); 59 //指定回調函數 60 myXmlHttpRequest.onreadystatechange=chuli; 61 //發送請求 62 myXmlHttpRequest.send(data); 63 64 } 65 66 67 } 68 69 function chuli(){ 70 if(myXmlHttpRequest.readyState==4){ 71 var mes= myXmlHttpRequest.responseText; 72 window.alert(mes); 73 var mes_obj=eval("("+mes+")"); 74 window.alert(mes_obj); 75 window.alert(mes_obj.ins[0].city); 76 // $('myres').value=mes_obj.info; 77 78 79 //取出xml格式數據 80 /* if(myXmlHttpRequest.status==200) 81 { 82 //取出服務器回送的數據 83 window.alert(myXmlHttpRequest.responseXML); 84 var cities= (myXmlHttpRequest.responseXML.getElementsByTagName("city")); 85 //window.alert(cities.length); 86 //alert(cities[1].lastChild.nodeValue); 87 for(var i=0;i<cities.length;i++) 88 {alert(cities[i].childNodes[0].nodeValue);} 89 } */ 90 91 } 92 93 } 94 95 96 function $(id) 97 { 98 return document.getElementById(id); 99 } 100 101 </script> 102 103 104 This is my JSP page. <br> 105 106 <select id="sheng" οnchange="getCities();"> 107 <option value="">---省---</option> 108 <option value="zhejiang">浙江</option> 109 <option value="jiangsu">江蘇</option> 110 </select> 111 112 <select id="city" οnchange="sendRequest();"> 113 <option value="">--城市--</option> 114 </select> 115 116 <select id="country" οnchange="sendRequest();"> 117 <option value="">--縣城--</option> 118 </select> 119 120 </body> 121 </html>2.xml格式
servlet代碼
1 package com.hsp.action; 2 3 import java.io.IOException; 4 import java.io.PrintWriter; 5 6 import javax.json.JsonString; 7 import javax.servlet.ServletException; 8 import javax.servlet.annotation.WebServlet; 9 import javax.servlet.http.HttpServlet; 10 import javax.servlet.http.HttpServletRequest; 11 import javax.servlet.http.HttpServletResponse; 12 13 /** 14 * Servlet implementation class showCities 15 */ 16 @WebServlet("/showCities") 17 public class showCities extends HttpServlet { 18 private static final long serialVersionUID = 1L; 19 20 /** 21 * @see HttpServlet#HttpServlet() 22 */ 23 public showCities() { 24 super(); 25 // TODO Auto-generated constructor stub 26 } 27 28 /** 29 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 30 */ 31 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 32 // TODO Auto-generated method stub 33 } 34 35 /** 36 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 37 */ 38 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 39 // TODO Auto-generated method stub 40 response.setContentType("text/xml;charset=utf-8"); 41 response.setHeader("Cache-Control", "no-cache"); 42 43 //接收用戶選擇的省的名字 44 String shengString=request.getParameter("province"); 45 System.out.println(shengString); 46 PrintWriter out=response.getWriter(); 47 StringBuilder builder=new StringBuilder(); 48 49 50 String info=""; 51 52 if ("zhejiang".equals(shengString)) { 53 System.out.println("浙江"); 54 info="<province><city>杭州</city><city>溫州</city><city>寧波</city></province>"; 55 } 56 else if ("jiangsu".equals(shengString)) { 57 System.out.println("江蘇"); 58 59 info="<province><city>南京</city><city>徐州</city><city>蘇州</city></province>"; 60 } 61 // if ("zhejiang".equals(shengString)) 62 // { 63 // info= "[{"+'"'+"city"+'"'+":"+'"'+"杭州"+'"'+"},{"+'"'+"city"+'"'+":"+'"'+"溫州"+'"'+"}]"; 64 // } 65 // else if ("jiangsu".equals(shengString)) { 66 // info= "[{"+'"'+"city"+'"'+":"+'"'+"南京"+'"'+"},{"+'"'+"city"+'"'+":"+'"'+"蘇州"+'"'+"}]"; 67 // 68 // } 69 // System.out.println("{"+'"'+"ins"+'"'+":"+info+"}"); 70 // builder.append("{"+'"'+"ins"+'"'+":"+info+"}"); 71 builder.append(info); 72 out.println(builder.toString()); 73 } 74 75 }jsp代碼
1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> 2 <% 3 String path = request.getContextPath(); 4 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; 5 %> 6 7 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> 8 <html> 9 <head> 10 <base href="<%=basePath%>"> 11 12 <title>My JSP 'Mycity.jsp' starting page</title> 13 14 <meta http-equiv="pragma" content="no-cache"> 15 <meta http-equiv="cache-control" content="no-cache"> 16 <meta http-equiv="expires" content="0"> 17 <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> 18 <meta http-equiv="description" content="This is my page"> 19 <!-- 20 <link rel="stylesheet" type="text/css" href="styles.css"> 21 --> 22 23 </head> 24 25 <body> 26 <script type="text/javascript"> 27 //1.創建ajax引擎 28 function getXmlHttpObject(){ 29 var xmlHttpRequest; 30 //不同的瀏覽器獲取對象xmlhttprequest對象方法不一樣 31 if(window.ActiveXobject) 32 { 33 xmlHttpRequest=new ActiveXobject("Microsoft.XMLHTTP"); 34 } 35 else 36 { 37 xmlHttpRequest=new XMLHttpRequest(); 38 } 39 return xmlHttpRequest; 40 } 41 42 //新建myXmlHttpRequest對象 43 var myXmlHttpRequest=""; 44 45 function getCities(){ 46 //創建對象 47 myXmlHttpRequest=getXmlHttpObject(); 48 // window.alert(myXmlHttpRequest); 49 //如果創建成功,則進行post請求 50 if(myXmlHttpRequest){ 51 //創建url 52 var url="/ajax/showCities";//post 53 //攜帶的參數 54 var data="province="+$('sheng').value; 55 // 56 myXmlHttpRequest.open("post",url,true); 57 //必填 58 myXmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); 59 //指定回調函數 60 myXmlHttpRequest.onreadystatechange=chuli; 61 //發送請求 62 myXmlHttpRequest.send(data); 63 64 } 65 66 67 } 68 69 function chuli(){ 70 if(myXmlHttpRequest.readyState==4){ 71 // var mes= myXmlHttpRequest.responseText; 72 /* window.alert(mes); 73 var mes_obj=eval("("+mes+")"); 74 window.alert(mes_obj); 75 window.alert(mes_obj.ins[0].city); */ 76 // $('myres').value=mes_obj.info; 77 78 79 //取出xml格式數據 80 if(myXmlHttpRequest.status==200) 81 { 82 //取出服務器回送的數據 83 window.alert(myXmlHttpRequest.responseXML); 84 var cities= (myXmlHttpRequest.responseXML.getElementsByTagName("city")); 85 //window.alert(cities.length); 86 //alert(cities[1].lastChild.nodeValue); 87 for(var i=0;i<cities.length;i++) 88 {alert(cities[i].childNodes[0].nodeValue);} 89 } 90 91 } 92 93 } 94 95 96 function $(id) 97 { 98 return document.getElementById(id); 99 } 100 101 </script> 102 103 104 This is my JSP page. <br> 105 106 <select id="sheng" οnchange="getCities();"> 107 <option value="">---省---</option> 108 <option value="zhejiang">浙江</option> 109 <option value="jiangsu">江蘇</option> 110 </select> 111 112 <select id="city" οnchange="sendRequest();"> 113 <option value="">--城市--</option> 114 </select> 115 116 <select id="country" οnchange="sendRequest();"> 117 <option value="">--縣城--</option> 118 </select> 119 120 </body> 121 </html>3.text格式
servlet 格式
1 package com.hsp.action; 2 3 import java.io.IOException; 4 import java.io.PrintWriter; 5 6 import javax.servlet.ServletException; 7 import javax.servlet.ServletOutputStream; 8 import javax.servlet.annotation.WebServlet; 9 import javax.servlet.http.HttpServlet; 10 import javax.servlet.http.HttpServletRequest; 11 import javax.servlet.http.HttpServletResponse; 12 13 /** 14 * Servlet implementation class registerServlet 15 */ 16 @WebServlet("/registerServlet") 17 public class registerServlet extends HttpServlet { 18 private static final long serialVersionUID = 1L; 19 20 /** 21 * @see HttpServlet#HttpServlet() 22 */ 23 public registerServlet() { 24 super(); 25 // TODO Auto-generated constructor stub 26 } 27 28 /** 29 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) 30 */ 31 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 32 // TODO Auto-generated method stub 33 34 //接受數據 35 //String username=request.getParameter("username"); 36 //System.out.println(username); 37 String infoString=""; 38 if ("shunping".equals("")) { 39 infoString="用戶名不可用"; 40 } 41 else { 42 infoString="用戶名可用"; 43 44 } 45 //返回文本數據 46 // response.setContentType("text/;charset=utf-8"); 47 //返回xml格式文件 48 response.setContentType("text/xml;charset=utf-8"); 49 50 response.setHeader("Cache-Control", "no-cache"); 51 52 53 //返回xml 格式數據 54 PrintWriter out=response.getWriter(); 55 StringBuilder builder=new StringBuilder(); 56 // builder.append("<message>"); 57 // builder.append(infoString).append("</message>"); 58 59 // builder.append( "{"+'"'+"info"+'"'+":" ).append('"'+infoString+'"'+"}"); 60 builder.append(infoString); 61 out.println(builder.toString()); 62 63 //返回text格式數據 64 // ServletOutputStream outputStream = response.getOutputStream(); 65 // outputStream.write(infoString.getBytes("utf-8")); 66 // //outputStream.write(pwd.getBytes("utf-8")); 67 // outputStream.flush(); 68 // outputStream.close(); 69 } 70 71 /** 72 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) 73 */ 74 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 75 // TODO Auto-generated method stub 76 doGet(request, response); 77 } 78 79 }jsp格式
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html><head><base href="<%=basePath%>"><title>My JSP 'index.jsp' starting page</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">--></head><body><script type="text/javascript">//創建ajax引擎 function getXmlHttpObject(){var xmlHttpRequest;//不同的瀏覽器獲取對象xmlhttprequest對象方法不一樣if(window.ActiveXobject){xmlHttpRequest=new ActiveXobject("Microsoft.XMLHTTP");}else{xmlHttpRequest=new XMLHttpRequest();}return xmlHttpRequest;}var myXmlHttpRequest=null;//驗證用戶名是否存在 function checkName(){myXmlHttpRequest=getXmlHttpObject();// window.alert(myXmlHttpRequest);if(myXmlHttpRequest ){// window.alert("創建成功");//通過myXmlHttpRequest對象發送請求到服務器的某個頁面//1.第一個參數表示請求的方式,"get"/"post"//2.第二個參數指定url,對哪個頁面發出ajax請求(本質仍然是http請求)//3.第三個參數 true表示使用異步機制,如果false,表示不使用異步var url="/ajax/registerServlet?mytime="+new Date()+"&username="+$("username").value//打開請求myXmlHttpRequest.open("post",url,true);//window.alert(url);//指定回調函數,chuli 是函數名myXmlHttpRequest.onreadystatechange=chuli;//真的發送函數,如果是get請求,則填入null即可//如果是post請求,則填入實際的數據myXmlHttpRequest.send(null); }}//回調函數 function chuli(){//window.alert("處理函數被調用"+myXmlHttpRequest.readyState);//取出從serlet返回的數據if(myXmlHttpRequest.readyState==4){//取出值,文本格式//window.alert("服務器返回"+myXmlHttpRequest.responseText)////window.alert( "xml:"+myXmlHttpRequest.responseXML);//獲取message節點// var mes=myXmlHttpRequest.responseXML.getElementsByTagName("message");//window.alert(mes.length);//取出message節點//es[0]-->表示取出第一個message節點//childNodes[0]表示message節點的第一個子節點// var mes_val=mes[0].childNodes[0].nodeValue;//window.alert(mes_val);// ${'myres'}.value= mes_val;//$('myres').value=myXmlHttpRequest.responseText;/* var mes= myXmlHttpRequest.responseText;window.alert(mes);var mes_obj=eval("("+mes+")");//window.alert(mes_obj.info);$('myres').value=mes_obj.info;*/var mes= myXmlHttpRequest.responseText;$('myres').value=mes;} }function $(id){return document.getElementById(id);}</script>This is my JSP page. <br><form action="???" method="post">用戶名:<input type="text"name="username1" οnkeyup="checkName();" id="username"><input type="button" οnclick="checkName();" value="驗證用戶名"><input style="border-width: 0;color: red" type="text" id="myres"><br>用戶密碼:<input type="password" name="password"><br>電子郵件:<input type="text" name="email"><br><input type="submit" value="用戶注冊"> </form></body> </html>?
轉載于:https://www.cnblogs.com/albertfg/p/8031599.html
總結
以上是生活随笔為你收集整理的ajax 三种数据格式的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: spark rdd Transforma
- 下一篇: JFrame 居中显示