基於jquery非同步傳輸json資料格式執行個體代碼_jquery

來源:互聯網
上載者:User

1.jsp代碼如下

複製代碼 代碼如下:

<%@ 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>編號</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">
 <div  id="result"></div>
 <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.效果如下:

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.