Ajax中利用jQuery簡單實現異步交互

function verify(){
//	alert("被點擊了。。。。。。。");
	
	//得到id爲loginName的標籤對象
	var jqObject = $("#loginName");
	//得到文本框中的值
	var name = jqObject.val();
	//用JQ中的$.get()方法去訪問服務器
	/*JQ中的get方法接受的參數
	 * get(url, [data], [callback], [type])
	 * url 待載入頁面的URL地址
	 * data (可選) 待發送 Key/value 參數。
	 * callback (可選) 載入成功時回調函數。
	 * type (可選) 返回內容格式,xml, html, script, json, text, _default。
	 */
	$.get("AjaxTestServlet?loginName=" + name,null,callback);
}

//從服務器返回來的數據封裝在callback函數的參數中
function callback(data){
	alert(data);
}


主頁html爲如下

<!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=GBK">
<title>Insert title here</title>
<script type="text/javascript" src="jquery-1.7.1.js"></script>
<script type="text/javascript" src="verify.js"></script>
</head>
<body>
	<form name="form1" action="AjaxTestServlet" method="POST">
		請輸入註冊用戶名: <input name="loginName" type="text" id="loginName">
		<input type="button" name="checkLoginName" value="有效性檢查"
			οnclick="verify()"><br>
	</form>
</body>
</html>

接受的響應的服務器端的程序爲AjaxTestServlet

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class AjaxTestServlet
 */
@WebServlet("/AjaxTestServlet")
public class AjaxTestServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public AjaxTestServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doPost(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// post按doGet()方法處理
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		//這裏假設已經註冊過了四位用戶
		String[] logined = {"admin","users","dywdyw","zhaom_916"};
		//接收從客戶端提交的loginName參數
		String loginName = request.getParameter("loginName");
		//創建一個存放響應內容的字符串
		String responseContext = "true";
		for (int i=0;i<logined.length;i++){
			//遍歷已註冊用戶列表,如果發現提交的註冊名已存在,則修改響應內容
			if (loginName.equals(logined[i]))responseContext = "false";
		}
		//將處理結果返回給客戶端
		out.println(responseContext);
		out.flush();
		out.close();
	}

}
中間遇到過一個小問題  就是要求js與html的編碼一致  不然會出現亂碼

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章