基于jquery异步传输json数据格式实例代码
代码如下:
<%@ page language="java" contenttype="text/html; charset=utf-8"
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" "https://www.w3.org/tr/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>insert title here</title>
<script type="text/javascript" src="<%=basepath%>js/jquery-1.8.1.js"></script>
</head>
<script type="text/javascript">
$(function(){
$("#getresult").click(function(){
$.ajax({
type:"post",
url:"<%=basepath%>jsonaction!getdata.action",
datatype:"json",
data:{'param1':$("#param1").attr("value"),'param2':$("#param2").attr("value")},
success:function(returndata){
var html = "<table border='1'><tr><td>编号</td><td>姓名</td><td>描述</td></tr>";
for(var i = 0; i < returndata.length; i++){
html += "<tr><td>"+returndata[i].id+"</td><td>"+returndata[i].name+"</td><td>"+returndata[i].description+"</td></tr>";
}
$("#result").html(html);
}
});
});
});
</script>
<body>
<input type="text" value="haha" id="param1">
<input type="text" value="hehe" id="param2">
<p id="result"></p>
<input type="button" value="获取" id="getresult">
</body>
</html>
2.访问 action代码如下
。 代码如下:
public class jsonaction extends actionsupport{
public void getdata() throws ioexception
{
httpservletrequest req = servletactioncontext.getrequest();
string p1 = req.getparameter("param1");
string p2 = req.getparameter("param2");
httpservletresponse rep = servletactioncontext.getresponse();
rep.setcontenttype("text/json;charset=utf-8");
printwriter pw = rep.getwriter();
string data = "[{\"id\":\"01\",\"name\":\"zhongqian\",\"description\":\""+p1+"\"},{\"id\":\"02\",\"name\":\"zhangsan\",\"description\":\""+p2+"\"}]";
pw.print(data);
pw.flush();
}
}
3.效果如下:
下一篇: on()方法绑定的事件执行两次的原因