ajax异步传递json
最快在做项目时,遇到了这样的问题,浏览器通过ajax方式异步传递JSON交互问题,会出现各种问题。经过几天的搜索,终于得到解决~
jsp页面:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'ajaxTest.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache"/>
<meta http-equiv="cache-control" content="no-cache"/>
<meta http-equiv="expires" content="0"/>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3"/>
<meta http-equiv="description" content="This is my page"/>
<script type="text/javascript" src="scripts/jquery-1.9.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$(".submit").click(function(){
$.ajax({
url:"getJsonAction2",
type:"POST",
dataType:"json",
contentType:"application/json;charset=utf-8",
success:function(returnData,status)
{
person1= returnData[0];
person2= returnData[1];
alert(person1.username);
alert(person2.username);
}
});
});
});
</script>
</head>
<body>
<input type="submit" value="getJson" class="submit" >
</body>
</html>
Action代码:
import java.io.PrintWriter;
import java.util.ArrayList;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import com.google.gson.Gson;
import com.opensymphony.xwork2.ActionSupport;
public class GetAjaxAction extends ActionSupport
{
@Override
public String execute() throws Exception
{
Person person1 = new Person();
person1.setUsername("zhangsan");
person1.setPassword("123456");
person1.setAge(16);
person1.setAddress("beijing");
Person person2 = new Person();
person2.setUsername("lisi");
person2.setPassword("123456");
person2.setAddress("shanghai");
person2.setAge(20);
ArrayList<Person> list= new ArrayList<Person>();
list.add(person1);
list.add(person2);
Gson gson= new Gson();
String result = gson.toJson(list);
System.out.println(result);
HttpServletResponse response =ServletActionContext.getResponse();
PrintWriter out= response.getWriter();
out.println(result);
out.flush();
out.close();
return null;
}
}
struts.xml配置:
<action name="getJsonAction2" class="com.fileupload.GetAjaxAction"></action>
结果页面:
返回的JSON的对象数组,这样就可以解决很多问题了~当然也可以从jsp传送数据到服务端,比$.ajax更好用的方法还有$.post()和$.load(),但都基于ajax()方法实现的,而且ajax()方法还有很多可选的参数,有兴趣的可以自己练习用下~