ajax之json小结

    xiaoxiao2024-12-20  11

    JSON 可以将 JavaScript 对象中表示的一组数据转换为字符串(伪对象),然后就可以在函数之间轻松地传递这个字符串, 或者在异步应用程序中将字符串从 Web 客户端传递给服务器端程序。简而言之,JSONj就是JavaScript交互数据的一种格式.

    从客户端向服务器传递对象:

    步骤: 1)在客户端将JSON对象转换为JSON格式字符串,调用json.js的函数:toJSONString() 2)服务端:将客户端发送过来的json格式字符串转换为java类对象 //step1:json格式字符串转为JSON对象 JSONObject jsonObject=JSONObject.fromObject(realVal); //step2:JSON对象转为Java对象 2.1)利用JSONObject.fromObject(realVal)函数,将json格式字符串转为JSON对象 2.2)利用JSONObject.toBean(jsonObject, Person.class)将JSON对象转为Java对象  示例: jsp代码: <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>将json对象格式字符串发送给服务器程序</title> <script type="text/javascript" src="script/json.js"></script> <script language="javascript"> //将JSON对象转换为JSON格式字符串 var student = {id:12,name:"小红帽",sex:"女",age:20}; //调用json.js的函数:toJSONString() var jsonString=student.toJSONString(); var url="serverAcceptJSON?val="+jsonString; url=encodeURI(encodeURI(url)); window.location=url; </script> </head> <body> </body> </html> java代码: import java.io.IOException; import java.io.PrintWriter; import java.net.URLDecoder; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONObject; public class ServerAcceptJSON extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String value=request.getParameter("val"); String realVal=URLDecoder.decode(value, "utf-8"); System.out.println(realVal); //将客户端发送过来的json格式字符串转换为java类对象 //step1:json格式字符串转为JSON对象 JSONObject jsonObject=JSONObject.fromObject(realVal); //step2:JSON对象转为Java对象 Person person = (Person)JSONObject.toBean(jsonObject, Person.class); System.out.println(person); } } 从客户端向服务器传递集合对象: 步骤: 1)在客户端将JSON集合对象转换为JSON格式字符串,调用json.js的函数:toJSONString() 2)服务端:将客户端发送过来的json格式字符串转换为java类集合对象 2.1)利用JSONArray.fromObject(realVal))函数,将json格式字符串转为JSON集合对象 2.2)利用Person[] strs= (Person[]) JSONArray.toArray(jsonArray,Person.class);将JSON集合对象转为Java集合 示例: jsp代码: <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>将json对象格式字符串发送给服务器程序</title> <script type="text/javascript" src="script/json.js"></script> <script language="javascript"> //将JSON对象转换为JSON格式字符串 var studentList = [ {id:12,name:"小红帽",sex:"女",age:20}, {id:13,name:"花痴",sex:"女",age:19}, {id:13,name:"小飞侠",sex:"男",age:22} ] //调用json.js的函数:toJSONString() var jsonString=studentList.toJSONString(); alert(jsonString); var url="serverAcceptJSON?val="+jsonString; url=encodeURI(encodeURI(url)); window.location=url; </script> </head> <body> </body> </html> java代码: import java.io.IOException; import java.io.PrintWriter; import java.net.URLDecoder; 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; public class ServerAcceptJSON extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String value=request.getParameter("val"); String realVal=URLDecoder.decode(value, "utf-8"); System.out.println(realVal); //将客户端发送过来的json格式字符串转换为java类对象 //step1:json格式字符串转为JSON对象 JSONArray jsonArray =JSONArray.fromObject(realVal); //step2:JSON对象转为Java对象 Person[] strs= (Person[]) JSONArray.toArray(jsonArray,Person.class); for(int i=0;i<strs.length;i++){ System.out.println(strs[i]); } } } 通过ajax异步请求服务器对象数据: 步骤: 1)从客户端发送ajxa的异步请求; 2)服务端:向客户端传递对象 2.1)把Java对象转换为JSON对象: JSONObject jsonObj=JSONObject.fromObject(p); 2.2)JSON对象转json格式的字符串 String jsonString=jsonObj.toString(); 3)客户端进行处理   3.1)将json字符串文本转换为json对象 var personObj=eval('(' + personStr + ')');      3.2)向表格中添加一行  var tbodyObj=document.getElementById("data");            var trObj=document.createElement("tr");            var tdObj1=document.createElement("td");            tdObj1.innerHTML=person.id;            var tdObj2=document.createElement("td");            tdObj2.innerHTML=person.name;            var tdObj3=document.createElement("td");            tdObj3.innerHTML=person.sex;            var tdObj4=document.createElement("td");            tdObj4.innerHTML=person.age;            trObj.appendChild(tdObj1);            trObj.appendChild(tdObj2);            trObj.appendChild(tdObj3);            trObj.appendChild(tdObj4);            tbodyObj.appendChild(trObj);            document.getElementById("tab_data").style.display="block"; 示例; jsp代码(如何动态添加表格中的行): <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>将json对象格式字符串发送给服务器程序</title> <script type="text/javascript" src="script/json.js"></script> <script language="javascript"> var xmlhttp; function createXMLHttp(){ xmlhttp= new XMLHttpRequest(); } function getPerson(){ createXMLHttp(); var url="queryPerson"; xmlhttp.open("get",url,true); xmlhttp.onreadystatechange=addPerson; xmlhttp.send(); } function addPerson(){ if(xmlhttp.readyState==4){ if(xmlhttp.status==200){ var personStr = xmlhttp.responseText; //将json字符串文本转换为json对象 var personObj=eval('(' + personStr + ')'); addRow(personObj); } } } function addRow(person){ if(person==null){ document.getElementById("lbl_msg").innerHTML= "<font color='red'>没有找到符合条件的数据!</font>"; return; } var tbodyObj=document.getElementById("data"); var trObj=document.createElement("tr"); var tdObj1=document.createElement("td"); tdObj1.innerHTML=person.id; var tdObj2=document.createElement("td"); tdObj2.innerHTML=person.name; var tdObj3=document.createElement("td"); tdObj3.innerHTML=person.sex; var tdObj4=document.createElement("td"); tdObj4.innerHTML=person.age; trObj.appendChild(tdObj1); trObj.appendChild(tdObj2); trObj.appendChild(tdObj3); trObj.appendChild(tdObj4); tbodyObj.appendChild(trObj); document.getElementById("tab_data").style.display="block"; } </script> </head> <body> <button οnclick="getPerson();">查询</button> <hr/> <label id="lbl_msg"></label> <table id="tab_data" style="display:none;"> <thead> <tr> <th>学号</th> <th>姓名</th> <th>性别</th> <th>年龄</th> </tr> </thead> <tbody id="data"> </tbody> </table> </body> </html> java代码: import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONObject; public class QueryPerson extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Person p = new Person(38,"胡微","女",22); //把Java对象转换为JSON格式字符串:"{id:38,name:'胡微',sex:'女',age:22}" JSONObject jsonObj=JSONObject.fromObject(p); String jsonString=jsonObj.toString(); response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); if(p==null){ out.println("null"); }else{ out.println(jsonString); } out.flush(); out.close(); } } 通过ajax异步请求服务器对象数组数据: 步骤: 1)从客户端发送ajxa的异步请求; 2)服务端:向客户端传递对象 2.1)把Java对象数组转换为JSON对象: JSONArray jsonarray=JSONArray.fromObject(perList); 2.2)JSON对象转json格式的字符串 String jsonString=jsonarray.toString(); 3)客户端进行处理   3.1)将json字符串文本转换为json对象 var personObj=eval('(' + personStr + ')');      3.2)向表格中添加一行    for(var i=0;i<person.length;i++){            var tbodyObj=document.getElementById("data");            var trObj=document.createElement("tr");            var tdObj1=document.createElement("td");            tdObj1.innerHTML=person[i].id;            var tdObj2=document.createElement("td");            tdObj2.innerHTML=person[i].name;            var tdObj3=document.createElement("td");            tdObj3.innerHTML=person[i].sex;            var tdObj4=document.createElement("td");            tdObj4.innerHTML=person[i].age;            trObj.appendChild(tdObj1);            trObj.appendChild(tdObj2);            trObj.appendChild(tdObj3);            trObj.appendChild(tdObj4);            tbodyObj.appendChild(trObj);            }            document.getElementById("tab_data").style.display="block"; jsp代码: <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>将json对象格式字符串发送给服务器程序</title> <script type="text/javascript" src="script/json.js"></script> <script language="javascript"> var xmlhttp; function createXMLHttp(){ xmlhttp= new XMLHttpRequest(); } function getPerson(){ createXMLHttp(); var url="queryPer"; xmlhttp.open("get",url,true); xmlhttp.onreadystatechange=addPerson; xmlhttp.send(); } function addPerson(){ if(xmlhttp.readyState==4){ if(xmlhttp.status==200){ var personStr = xmlhttp.responseText; alert(personStr); //将json字符串文本转换为json对象 var personObj=eval('(' + personStr + ')'); alert(personObj); addRow(personObj); } } } function addRow(person){ if(person==null){ document.getElementById("lbl_msg").innerHTML= "<font color='red'>没有找到符合条件的数据!</font>"; return; } for(var i=0;i<person.length;i++){ var tbodyObj=document.getElementById("data"); var trObj=document.createElement("tr"); var tdObj1=document.createElement("td"); tdObj1.innerHTML=person[i].id; var tdObj2=document.createElement("td"); tdObj2.innerHTML=person[i].name; var tdObj3=document.createElement("td"); tdObj3.innerHTML=person[i].sex; var tdObj4=document.createElement("td"); tdObj4.innerHTML=person[i].age; trObj.appendChild(tdObj1); trObj.appendChild(tdObj2); trObj.appendChild(tdObj3); trObj.appendChild(tdObj4); tbodyObj.appendChild(trObj); } document.getElementById("tab_data").style.display="block"; } </script> </head> <body> <button οnclick="getPerson();">查询</button> <hr/> <label id="lbl_msg"></label> <table id="tab_data" style="display:none;"> <thead> <tr> <th>学号</th> <th>姓名</th> <th>性别</th> <th>年龄</th> </tr> </thead> <tbody id="data"> </tbody> </table> </body> </html> java代码: package com.heres; 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 net.sf.json.JSONArray; import net.sf.json.JSONObject; public class QueryPerson extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("11111111"); Person p1 = new Person(38,"胡微","女",22); Person p2 = new Person(19,"汪洋","男",23); Person p3 = new Person(36,"胡八一","女",42); List<Person> perList = new ArrayList<Person>(); perList.add(p1); perList.add(p2); perList.add(p3); //把Java对象转换为JSON格式字符串:"{id:38,name:'胡微',sex:'女',age:22}" JSONArray jsonarray=JSONArray.fromObject(perList); String jsonString=jsonarray.toString(); System.out.println(jsonString); response.setContentType("text/html;charset=utf-8"); PrintWriter out = response.getWriter(); out.println(jsonString); out.flush(); out.close(); } }
    转载请注明原文地址: https://ju.6miu.com/read-1294804.html
    最新回复(0)