前台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><html><head><base href="<%=basePath%>"><title>My JSP 'jqueryajax.jsp' starting page</title><script type="text/javascript" src="js/jquery-1.7.2.min.js"></script><script type="text/javascript">function kk(){//得到ajax擷取到的資料,返回一個object var htmlobj=$.ajax({url:"servlet/JsonServlet",async:false}); //將 ajax object 轉換為json object,第二種轉換// htmlobj = jQuery.parseJSON(htmlobj.responseText); htmlobj = eval(htmlobj.responseText); //清空class 為 sj 的標籤內容 $(".sj").empty(); var html = '<table border="1"><tr><td>ID</td><td>使用者名稱</td><td>密碼</td></tr>'; //迴圈擷取資料並且拼接成html $.each(htmlobj,function(entryIndex,entry){ html += '<tr><td>'+entry['id']+'</td><td>' +entry['username']+'</td><td>' +entry['password']+'</td></tr>'; }); html += '</table>'; //附加內容到class 為 sj的標籤 $(".sj").append(html); }</script></head><body><div>Jquery 動態擷取資料 ,示範..</div><div class="sj"></div><input type="button" onclick="kk()" value="點擊" /></body></html>
後台一個Servlet 負責從mysql中擷取資料並且將其處理成JSONArray
package com.action;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import net.sf.json.JSONArray;public class JsonServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { Toto toto = new Toto();toto.selectAllUsers();JSONArray json = JSONArray.fromObject(toto.getUsers()); response.setCharacterEncoding("utf-8");PrintWriter pw = response.getWriter();pw.print(json);}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {doGet(request, response);}}
運行後的效果:
附加 :對於jquery非同步擷取資料還可以寫成這樣,如下:(推薦用這種寫法,個人覺得比較標準)
$.getJSON("servlet/JsonServlet",function(htmlobj){ $(".sj").empty(); var html = '<table>'; $.each(htmlobj,function(entryIndex,entry){ html += '<tr><td>'+entry['id']+'</td></tr>'; }); html += '</table>'; $(".sj").append(html); });}
還可以這樣寫:
$.ajax({url:'servlet/JsonServlet',type:'post',success:function(msg){var htmlobj = jQuery.parseJSON(msg);var html = '<table>';$.each(htmlobj,function(entryIndex,entry){ html += '<tr><td>'+entry['id']+'</td></tr>'; });html += '</table>'; $(".sj").html(html); }});