Jquery+ajax+json+servlet原理和Demo
大致過程:
使用者時間點擊,觸發js,設定$.ajax,開始請求。伺服器響應,擷取ajax傳遞的值,然後處理。以JSON格式返回給ajax。ajax在sucess對應的函數中將返回的json資料進行解析,然後輸出到jsp頁面。
1.前台index.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 PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html><head><base href="<%=basePath%>"><title>Jquery Ajax Json Servlet Demo</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0"><meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">--><script type="text/javascript" src="js/jquery.min.js"></script><script type="text/javascript"> function jsonAjaxPost(){ var userNameObj=$("#username").val(); var contentObj=$("#content").val(); $.ajax({ type:"post",//請求方式 url:"jsonAjaxAction?userName="+encodeURI(encodeURI(userNameObj)) +"&content="+encodeURI(encodeURI(contentObj)),//發送請求地址 timeout:30000,//逾時時間:30秒 dataType:"json",//設定返回資料的格式 //請求成功後的回呼函數 data為json格式 success:function(data){ $("#resultJsonText").text("你的名字:"+data.yourName+" 你輸入的內容:"+data.yourContent); }, //請求出錯的處理 error:function(){ alert("請求出錯"); } }); }</script></head><body><form id="form1" method="post"><p>評論:</p><p>姓名:<input type="text" name="username" id="username" /></p><p>內容:<textarea name="content" id="content" rows="2" cols="20"></textarea></p><p><input type="button" id="send" value="提交" onclick="jsonAjaxPost()" /></p></form><div class="comment">返回資料:<p id="resultJsonText"></p></div><div id="resText"></div></body></html>
2.後台Servlet
/* * $filename: JsonAjaxServlet.java,v $ * $Date: Sep 1, 2013 $ * Copyright (C) ZhengHaibo, Inc. All rights reserved. * This software is Made by Zhenghaibo. */package com.njupt.zhb.test;import java.io.IOException;import java.io.PrintWriter;import java.net.URLDecoder;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/* *@author: ZhengHaibo *web: http://blog.csdn.net/nuptboyzhb *mail: zhb931706659@126.com *Sep 1, 2013 Nanjing,njupt,China */public class JsonAjaxServlet extends HttpServlet{/** * */private static final long serialVersionUID = 1L;@Overrideprotected void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// TODO Auto-generated method stubdoPost(request, response);}@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {// TODO Auto-generated method stubrequest.setCharacterEncoding("utf-8");String userName = request.getParameter("userName");userName=URLDecoder.decode(userName, "UTF-8");String content = request.getParameter("content");content=URLDecoder.decode(content, "UTF-8");System.out.println("userName:"+userName);System.out.println("content:"+content);response.setCharacterEncoding("utf-8");PrintWriter out = response.getWriter();//將資料拼接成JSON格式out.print("{\"yourName\":\"" + userName + "\",\"yourContent\":\""+content+"\"}");out.flush();out.close();}}
3.設定檔web.xml
<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <servlet><servlet-name>jsonAjaxAction</servlet-name><servlet-class>com.njupt.zhb.test.JsonAjaxServlet</servlet-class></servlet><servlet-mapping><servlet-name>jsonAjaxAction</servlet-name><url-pattern>/jsonAjaxAction</url-pattern></servlet-mapping></web-app>
4.其他
1.需要匯入jquery.min.js
2.注意亂碼的解決方案:
2.1:js中對字串進行編碼,即:encodeURI(encodeURI(userNameObj))
2.2:在Servlet中需要用java.net.URLDecoder解碼
5.結果示範 :
在瀏覽器中輸入:http://localhost:8080/AjaxServletJson/
先輸入,然後點擊按鈕:
原始碼下載:http://download.csdn.net/detail/nuptboyzhb/6193851
參考資料:
1.jquery $.ajax參考手冊:http://www.w3school.com.cn/jquery/ajax_ajax.asp
未經允許不得用於商業目的