此例client端利用JQuery的Ajax語法來將表單中的參數傳給以Servlet實作的Server端,經由Server端處理過後,以JSON的格式回傳給client端, client端再將JSON格式的回傳值解析後做相應的動作,此例的動作為兩個:跳出視窗顯示回傳值、在html裡的filedset中顯示回傳值。
- 首先是作為client端的html內容,index.html:
- 再來是Server端的Servlet,doAjaxServlet.java:
<!DOCTYPE html>
<html>
<head>
<title>AjaxTest</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- 加載Ajax -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<!-- Ajax的測試Script -->
<script>
//在網頁加載後,對id=doAjaxBtn的Button設定click的function
$(document).ready(function(){
$("#doAjaxBtn").click(function(){
$.ajax({
type:"POST", //指定http參數傳輸格式為POST
url: "doAjaxServlet.do", //請求目標的url,可在url內加上GET參數,如 www.xxxx.com?xx=yy&xxx=yyy
data: $("#formId").serialize(), //要傳給目標的data為id=formId的Form其序列化(serialize)為的值,之
//內含有name的物件value
dataType: "json", //目標url處理完後回傳的值之type,此列為一個JSON Object
//Ajax成功後執行的function,response為回傳的值
//此範列回傳的JSON Object的內容格式如右所示: {userName:XXX,uswerInterest:[y1,y2,y3,...]}
success : function(response){
//在id=ajaxResponse的fieldset中顯示Ajax的回傳值
$("#ajaxResponse").html("您的大名:"+response.userName+"</br>");
$("#ajaxResponse").append("您的興趣:</br>");
var userInterestString = "";
for(var i = 0 ; i<response.userInterest.length ; i++){
$("#ajaxResponse").append(response.userInterest[i]+"</br>");
userInterestString += "\n"+response.userInterest[i];
}
//用彈出視窗顯示Ajax的回傳值
alert("UserName:"+response.userName+"\nInterest: "+userInterestString);
},
//Ajax失敗後要執行的function,此例為印出錯誤訊息
error:function(xhr, ajaxOptions, thrownError){
alert(xhr.status+"\n"+thrownError);
}
});
});
});
</script>
</head>
<body>
<div>AjaxTest</div>
<form id="formId">
大名:<input type="text" name="userName">
<input type="checkbox" name="userInterest" value="看書" />看書
<input type="checkbox" name="userInterest" value="遊戲" />遊戲
<input type="checkbox" name="userInterest" value="電影" />電影
<input type="button" id="doAjaxBtn" value="啟動Ajax" />
</form>
<div id="anotherSection">
<!-- 用來顯示Ajax回傳值的fieldset -->
<fieldset>
<legend>Response from jQuery Ajax Request</legend>
<div id="ajaxResponse"></div>
</fieldset>
</div>
</body>
</html>
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONObject;
@WebServlet(urlPatterns = {"/doAjaxServlet.do"})
public class doAjaxServlet extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
//對Post中文參數進行解碼
request.setCharacterEncoding("UTF-8");
//取得Ajax傳入的參數
String userName = request.getParameter("userName");
String[] arrayUserInterest = request.getParameterValues("userInterest");
//建構要回傳JSON物件
HashMap userInfoMap = new HashMap();
userInfoMap.put("userName", userName);
ArrayList userInterestList = new ArrayList();
userInterestList.addAll(Arrays.asList(arrayUserInterest));
userInfoMap.put("userInterest", userInterestList);
JSONObject responseJSONObject = new JSONObject(userInfoMap);
PrintWriter out = response.getWriter();
out.println(responseJSONObject);
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
一開始的畫面:
沒有選擇checkbox或沒輸入名字就按下按鈕的結果:
有輸入名字及選擇checkbox時按下按鈕的結果:
最後附上原始碼:




這篇對我的幫助很大!謝謝!:)
回覆刪除nice post !
回覆刪除