导读:
摘要: Ajax Lesson3 与服务器交互 使用JSON封装传递数据. ——点击此处阅读全文
本文转自
http://blog.youkuaiyun.com/booby_fly
一.客户段主要代码
二.服务器端主要代码
protected void doProcess(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String json=readXMLFromRequestBody(request);
JSONObject jsobObject=null;
String responseText="";
try
{
jsobObject=new JSONObject(json);//通过字串生成对象后可
//使用Get Set设置值.
responseText="You Hava a "+jsobObject.getInt("year")+" "+jsobObject.getString("make")+" "+jsobObject.getString("model")+" "+
jsobObject.getString("color");
}catch(Exception ex)
{
ex.printStackTrace();
}
response.setContentType("text/xml");
response.getWriter().println(responseText);
}
//从请求对象里读出提交过来的字串.命名不规范因为之前使用过
private String readXMLFromRequestBody(HttpServletRequest request)
{
StringBuffer xml=new StringBuffer();
String line=null;
try
{
BufferedReader reader=request.getReader();
while((line=reader.readLine())!=null)
{
xml.append(line);
}
}catch(Exception ex)
{
ex.printStackTrace();
}
return xml.toString();
}
三.实现步骤:
1.到JSON上(www.json.org)下载程序所用的到包.一个jar一个js文件 .放到工程中供调用.
2,注意js中创建一个对象的方法是用 new function实现的.
3.使用fiddler 查看网页传输数据可以看处详细的数据.JSON只是做了个2端的封装达到数据比XML少.实现方便的效果.其传输的实质不变.
本文介绍了一个使用Ajax通过JSON格式与服务器交互的示例。客户端发送包含汽车信息的对象,服务器接收并解析该对象,并返回处理结果。
407

被折叠的 条评论
为什么被折叠?



