問題所在:
當(dāng)我們想讓應(yīng)用層和http之間的所有接口都采用json,這樣,客戶端代碼就可以純碎用javascript的對象來編寫,服務(wù)器打啊也可以純粹的用Java的對象來編寫。
我們使用的是post請求的方法,有些不同于get的方法!
客戶端html代碼:
<html><head><title>Hello Ajax version 5a</title><style type='text/css'>* { font-family: Tahoma, Arial, sans-serif; }#helloTitle{ color: #48f; }.sidebar{ background-color: #adf; color: navy; border: solid blue 1px; width: 180px; height: 200px; padding: 2px; margin: 3px; float: left;}</style><script type='text/javascript' src='prototype.js'></script><script type='text/javascript' src='json.js'></script><script type='text/javascript'>window.onload=function(){ $('helloBtn').onclick=function(){ var name=$('helloTxt').value; new Ajax.Request( "hello5a.jsp", { postBody:JSON.stringify({name:name}), onComplete:function(xhr){ var responseObj=JSON.parse(xhr.responseText); update(responseObj); } } ); }}function update(obj){ $('helloTitle').innerHTML="<h1>Hello, <b><i>"+obj.name+"</i></b></h1>"; var likesHTML='<h5>'+obj.initial+' likes...</h5><hr/>'; for (var i=0;i<obj.likes.length;i++){ likesHTML+=obj.likes[i]+"<br/>"; } $('likesList').innerHTML=likesHTML; var recipeHTML='<h5>'+obj.initial+'/'s favourite recipe</h5>'; for (key in obj.ingredients){ recipeHTML+=key+" : "+obj.ingredients[key]+"<br/>"; } $('ingrList').innerHTML=recipeHTML;}</script></head><body><div id='likesList' class='sidebar'><h5>Likes</h5><hr/></div><div id='ingrList' class='sidebar'><h5>Ingredients</h5><hr/></div><div><div id='helloTitle'><h1>Hello, stranger</h1></div><p>Please introduce yourself by entering your name in the box below</p><input type='text' size='24' id='helloTxt'></input> <button id='helloBtn'>Submit</button></div></body></html>
jsp代碼:
<jsp:directive.page contentType="application/javascript" import="java.util.*,net.sf.json.*"/><%//read the request bodyString json=request.getReader().readLine(); //讀取post請求主體JSONObject jsonObj=new JSONObject(json);//解析json字符串String name=(String)(jsonObj.get("name"));//讀取解析后的對象jsonObj.put("initial",name.substring(0,1).toUpperCase()); //添加新的值String[] likes=new String[]{ "JavaScript", "Skiing", "Apple Pie" };jsonObj.put("likes",likes);Map ingredients=new HashMap();ingredients.put("apples","3kg");ingredients.put("sugar","1kg");ingredients.put("pastry","2.4kg");ingredients.put("bestEaten","outdoors");jsonObj.put("ingredients",ingredients);%><%=jsonObj%> <!--以json的形式輸出對象-->
另外我們還要用到包裝集:
prototype.js
和json.js
效果如下:
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,謝謝大家對武林網(wǎng)的支持。如果你想了解更多相關(guān)內(nèi)容請查看下面相關(guān)鏈接
新聞熱點
疑難解答