Abd*_*lah 5 ajax jquery jsp servlets
我有一个简单的jsp/servlet应用程序,我想为这个应用程序添加AJAX功能.我使用JQuery,但我使用的javascript框架并不重要.这是我的代码:
<script type="text/javascript">
function callbackFunction(data){
$('#content').html(data);
}
$('document').ready(function(){
$('#x').click(function() {
$.post('/ajax_2/servlet',callbackFunction)
});
});
</script>
<body>
<a href="#" id="x">Increase it</a>
<div id="content"></div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
Servlet的
HttpSession session = request.getSession();
Integer myInteger = (Integer)session.getAttribute("myInteger");
if(myInteger == null)
myInteger = new Integer(0);
else
myInteger = new Integer(myInteger+1);
session.setAttribute("myInteger", myInteger);
response.getWriter().println(myInteger);
Run Code Online (Sandbox Code Playgroud)
问题:
我使用out.print将数据从servlet传输到javascript代码(ajax代码),但是如果我有一个复杂的结构,比如Vector of Objects或类似的东西,那么传输数据的最佳方法是什么?怎么样的XML文件,JSON?是否有任何特殊的 jsp/servlets库将数据从servlet传输到ajax应用程序?如何在callbackFunction中解析这些数据?
最好的方法是使用JSON.有几个Java库可以将完整的Java对象转换为JSON字符串,反之亦然.可以在Javascript中以完全自然的方式访问JSON,而无需以其他格式转换/按摩数据.
至于服务器端部分,我强烈建议选择Google Gson作为JSON序列化程序.Gson是首选,因为它支持将复杂的Javabeans和数组,集合和它们的映射转换为JSON,反之亦然,而不需要在一行代码中轻松完成.它甚至支持泛型.基本上你需要做的就是以下几点:
String json = new Gson().toJson(object);
Run Code Online (Sandbox Code Playgroud)
查看用户指南以了解有关Gson功能的更多信息.
总而言之,服务器端的以下内容就足够了:
public static void writeJson(HttpServletResponse response, Object object) throws IOException {
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(new Gson().toJson(object));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8042 次 |
| 最近记录: |