Ajax的总结--JSON
发布时间:2020-12-16 00:37:19 所属栏目:百科 来源:网络整理
导读:第一种:传递object到服务器端,服务器也返回object到client端 ============================================================= client代码 ---------------------- var person=new Object(); person.name="郭强"; person.age=30; person.birthday=new Date
============================================================= client代码 ---------------------- var person=new Object(); person.name="郭强"; person.age=30; person.birthday=new Date(); var json=person.toJSONString(); var xml=new ActiveXObject("Microsoft.XMLHTTP"); xml.open("POST","<%=request.getContextPath()%>/json_server.jsp",true); xml.setrequestheader("content-type","application/x-www-form-urlencoded");//这句话很重要哦 xml.onreadystatechange=function() { if (xml.readyState==4) { //获得服务器端的json返回值 var result=xml.responseText; alert(result); //alert(result.parseJSON().name); alert(eval_r("("+result+")").name); } }; //把json对象传入 xml.send('json='+json); server端代码 ----------------------------- //以上是获得客户端传入的json字符串 request.setCharacterEncoding("UTF-8"); String json = request.getParameter("json"); System.out.println(json); JSONObject jsonObject = new JSONObject(json); System.out.println(jsonObject); //以下是向客户端返回json对象 Map person = (Map) JSONObject.toBean(jsonObject,HashMap.class); json=JSONObject.fromMap(person).toString(); System.out.println(json); out.write(json); 第一种:传递数组到服务器端,服务器也返回数组到client端 ============================================================= client代码 --------------------------- var person=new Object(); person.name="郭强"; person.age=30; person.birthday=new Date(); var arr=new Array(); arr.push(person); var json=arr.toJSONString(); var xml=new ActiveXObject("Microsoft.XMLHTTP"); xml.open("POST","<%=request.getContextPath()%>/json_array_server.jsp","application/x-www-form-urlencoded"); xml.onreadystatechange=function() { if (xml.readyState==4) { //获得服务器端的json返回值 var result=xml.responseText; alert(result); alert(result.parseJSON()[0].name); } }; //把json对象传入 xml.send('json='+json); server端代码 ----------------------------- //以上是获得客户端传入的json字符串 request.setCharacterEncoding("UTF-8"); String json = request.getParameter("json"); System.out.println(json); JSONArray jsonArray = new JSONArray(json); Object[] obj = jsonArray.toArray(); System.out.println(obj[0].toString()); //以下是向客户端返回json对象 json=jsonArray.toString(); System.out.println(json); out.write(json);
1.ajax中的传输对象只能用json格式的字符串; 2.eval方法就是将字符串作为json对象来执行,eval("+jsonString+"); PS:不少人使用json时可能会提示一个net.sf.ezmorph.xxx找不到,这是因为你的lib里面没有添加ezmorph.xx.jar。使用json需要的jar为:commons-beanutils.jar、commons-httpclient-3.0.1.jar、commons-lang-2.0.jar、ezmorph-1.0.jar、json-lib-0.9.jar、morph-1.0.1.jar。注意版本不一定要和我的一样。(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |