当前位置: 移动技术网 > IT编程>开发语言>JavaScript > 基于jquery异步传输json数据格式实例代码

基于jquery异步传输json数据格式实例代码

2019年04月17日  | 移动技术网IT编程  | 我要评论
代码如下: <%@ page language="java" contenttype="text/html; charset=utf-8&

代码如下:


<%@ 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.效果如下:

\

如您对本文有疑问或者有任何想说的,请 点击进行留言回复,万千网友为您解惑!

相关文章:

验证码:
移动技术网