现在的位置: 首页 > 综合 > 正文

使用json往返传输数据 post方法

2014年09月24日 ⁄ 综合 ⁄ 共 2253字 ⁄ 字号 评论关闭

问题所在:

当我们想让应用层和http之间的所有接口都采用json,这样,客户端代码就可以纯碎用javascript的对象来编写,服务器打啊也可以纯粹的用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 body
String 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

效果如下:

抱歉!评论已关闭.