Asynchronous transmission of json data format instance code based on jquery

  • 2020-03-29 23:57:55
  • OfStack

1. The JSP code is as follows


<%@ 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" "http://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> Serial number </td><td> The name </td><td> describe </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">
 <div  id="result"></div>
 <input type="button" value=" To obtain " id="getResult">
</body>
</html>

2. Access the action code as follows


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. The effect is as follows:

< img border = 0 SRC = "/ / files.jb51.net/file_images/article/201311/20131123145356357.png" >


Related articles: