Ajax被認爲是(Asynchronous JavaScript and XML的縮寫)。 容許瀏覽器與服務器通訊而無須刷新當前頁面的技術都被叫作Ajax。javascript
Ajax的核心是JavaScript對象XmlHttpRequest。XmlHttpRequest使您能夠使用JavaScript向服務器提出請求並處理響應,而不阻塞用戶。html
1.首先創建一個jsp頁面,導入js頁面而且新建一個測試按鈕。java
<script type="text/javascript" src="ajaxGet.js"></script> <!-- src導入相應的JavaScript實現Ajax代碼 --> </head> <body> <input type="button" id="btn" value="ajax"/> <!-- 測試按鈕 --> </body>
獲取XmlHttpRequest對象 function getXMLHttpRequest() { var xmlHttpReq=null; if (window.XMLHttpRequest) {//Mozilla 瀏覽器 xmlHttpReq = new XMLHttpRequest(); }else { if (window.ActiveXObject) {//IE 瀏覽器 try { xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { try {//IE 瀏覽器 xmlHttpReq = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { } } } } return xmlHttpReq;
window.onload = function(){ var btnDom=document.getElementById("btn"); btnDom.onclick = function(){ //ajax步驟 //1 var xhr = getXMLHttpRequest(); //2.監聽響應 如何判斷可以正確請求和響應 xhr.onreadystatechange = function(){ if(xhr.readyState == 4){ //響應結束 if(xhr.status == 200){ //正確響應 //接收響應數據 var data = xhr.responseText; alert(data); } } }; //3.打開鏈接 /* * method: get 或 post * url: 請求路徑 * async: true(表示異步,默認) false */ xhr.open("get","../ajaxGetServlet?age=18&userName=jack",true); //4.發送數據 xhr.send(null); //使用get請求send發送的數據都爲null,且不能省略這一步 }; };
window.onload = function(){ var btnDom=document.getElementById("btn"); btnDom.onclick = function(){ //1 var xhr = getXMLHttpRequest(); //2. xhr.onreadystatechange = function(){ if(xhr.readyState == 4){ if(xhr.status == 200){ var data = xhr.responseText; alert(data); } } }; //3. xhr.open("post","../ajaxPostServlet",true); /* * 4.發送數據 * send() string或null * String類型通常爲鍵值對 "username=zhangsan" * get請求 都是send(null) * post請求要send數據須要設置請求頭 */ xhr.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); xhr.send("user=admin&age=12"); }; };
public class AjaxGetServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String age = request.getParameter("age"); String userName = request.getParameter("userName"); System.out.println(age+"------"+userName); //響應數據 response.getWriter().print("hello"); //js中步驟2監聽響應 } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
代碼寫完之後,咱們只須要按一下(value="ajax")測試按鈕就能夠使用ajax技術實現異步請求與響應。jquery
<script type="text/javascript" src="../js/jquery-1.8.3.js"></script><!-- 導入jQuery包 --> <body> <h3>jquery 實現 ajax</h3> <p>用戶名:<input id="userName" name="userName"/><span id="msg"></span></p> <script type="text/javascript" src="jqdemo.js"></script><!-- jqdemo.js使用jquery實現ajax --> </body>
$(function(){ $("#userName").blur(function(){ var name = $(this).val(); if(name.trim() == ""){ return; } //jquery 實現 ajax $.ajax({ url:"../jqueryUserName", //請求的路徑 type:"post", // 請求方式 默認是get data: { //要發送的數據 "name":name }, dataType:"text", //響應數據的類型 success:function(result){ // 正確響應 if(result == "yes"){ $("#msg").html("用戶名能夠使用"); }else{ $("#msg").html("用戶名被佔用"); } }, error:function(){ alert("請求失敗!"); } }); }); });
public class JqueryUserName extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("jquery ajax 驗證用戶名!"); PrintWriter out = response.getWriter(); String name = request.getParameter("name"); if("ajax".equals(name) || "admin".equals(name) || "jack".equals(name)){ //用戶名已被使用 out.print("no"); }else{ out.print("yes"); } } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }