JSON—在服务器上生成JSON

来源:互联网 发布:宣传片制作软件 编辑:程序博客网 时间:2024/06/03 05:44

我们希望服务器能以结构化数据的形式响应我们的请求,并由客户端来决定如何呈现这些数据。

1.客户端代码:

<html><head><title>Hello Ajax version5</title><style type='test/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'>window.onload=function(){$('helloBtn').onclick=function(){var name=${'helloTxt'}.value;//新建一个ajax异步请求new Ajax.Request{"hello5.jsp?name=""+encodeURI(name),{//get方式提交method:"get",//等服务器端处理好json数据后,响应下面的函数onComplete:function(xhr){var responseObj=eval("("+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 favorite 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>

这样一种使用JSON的方式是相当简单的。我们用eval()来解析JSON响应。

2.服务器端的代码:

<jsp:directive.page contentType="application/javascript"/><%String name=request.getParameter("name");%>{name:"<%=name>",initial:"<%=name.substring(0,1).toUpperCase()%>",likes:["JavaScript","Skiing","Apple Pie"],ingredients:{apples:"3kg",sugar:"1kg",pastry:"2.4kg",bestEaten:"outdoors"}}

整个流程是,在客户端输入一名字后,点击提交,服务器端会接收该参数,并将名字的第一位切下来赋给initial。而当服务器端解析完整个jsp页面后,客户端的onComplete function(xhr)启动,并接收JSON数据集合,交给update()函数处理。

原创粉丝点击