当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 使用post方法实现json往返传输数据的方法

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

2019年07月25日  | 移动技术网IT编程  | 我要评论

问题所在:

当我们想让应用层和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.jsjson.js

效果如下:

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对移动技术网的支持。如果你想了解更多相关内容请查看下面相关链接

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网