Ajax解決多余刷新的兩種方法(總結(jié))
控制器Servlet則提供了簡單的改變:
對于Ajax系統(tǒng)而言,服務(wù)器響應(yīng)無須是整個頁面內(nèi)容,可以僅是
必需的數(shù)據(jù),控制器不能將數(shù)據(jù)請求轉(zhuǎn)發(fā)到j(luò)sp頁面。
此時控制器有兩個選擇:
1、直接生成簡單的響應(yīng)數(shù)據(jù)。
在這種模式下,Servlet直接通過response獲取頁面輸出流,通過
輸出流生成字符響應(yīng)。
package pers.zkr.chat.web; 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; import pers.zkr.chat.service.ChatService; @WebServlet(urlPatterns={"/chat.do"}) public class ChatServlet extends HttpServlet { @Override public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub request.setCharacterEncoding("utf-8"); String msg=request.getParameter("chatMsg"); System.out.println(msg); if(msg!=null&&!msg.equals("")){ String user=(String)request.getSession().getAttribute("user"); System.out.println(user+"user"); ChatService.instance().addMsg(user, msg); } //設(shè)置響應(yīng)內(nèi)容的類型 <strong>response.setContentType("text/html;charset=utf-8"); // 獲取頁面輸出流 PrintWriter out = response.getWriter(); //直接生成響應(yīng) out.println(ChatService.instance().getMsg());</strong> request.setAttribute("msg",ChatService.instance().getMsg()); forward("/chat.jsp", request , response); } private void forward(String url, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub request.getRequestDispatcher(url) .forward(request , response); } }
2、轉(zhuǎn)向一個簡單的jsp使用JSP頁面生成簡單的響應(yīng)。
控制器將請求轉(zhuǎn)發(fā)到另外的JSP頁面,而JSP頁面僅僅負(fù)責(zé)輸出聊天信息
在這里需要一個jsp頁面來接收控制器發(fā)來的數(shù)據(jù),也是服務(wù)器的響應(yīng)文本,而在
原來的頁面,只需:
1)創(chuàng)建XMLHttpRequest對象
2) 發(fā)送請求
3)接收服務(wù)器的響應(yīng)
package org.crazyit.chat.web; import javax.servlet.*; import javax.servlet.http.*; import javax.servlet.annotation.*; import java.io.*; import org.crazyit.chat.service.*; /** * Description: * <br/>網(wǎng)站: <a href=http://www.dbjr.com.cn>腳本之家</a> * <br/>Copyright (C), 2001-2014, Yeeku.H.Lee * <br/>This program is protected by copyright laws. * <br/>Program Name: * <br/>Date: * @version 1.0 */ @WebServlet(urlPatterns={"/chat.do"}) public class ChatServlet extends HttpServlet { public void service(HttpServletRequest request, HttpServletResponse response)throws IOException,ServletException { // 設(shè)置使用GBK字符集來解析請求參數(shù) request.setCharacterEncoding("utf-8"); String msg = request.getParameter("chatMsg"); if ( msg != null && !msg.equals("")) { // 取得當(dāng)前用戶 String user = (String)request.getSession(true) .getAttribute("user"); // 調(diào)用ChatService的addMsg來添加聊天消息 ChatService.instance().addMsg(user , msg); } // 將全部聊天信息設(shè)置成request屬性 <strong>request.setAttribute("chatList" , ChatService.instance().getMsg());</strong> // 轉(zhuǎn)發(fā)到chatreply.jsp頁面 forward("/chatreply.jsp" , request , response); } // 執(zhí)行轉(zhuǎn)發(fā)請求的方法 private void forward(String url , HttpServletRequest request, HttpServletResponse response)throws ServletException,IOException { // 執(zhí)行轉(zhuǎn)發(fā) request.getRequestDispatcher(url) .forward(request,response); } }
接收數(shù)據(jù)的頁面
<%@ page contentType="text/html;charset=GBK" errorPage="error.jsp"%> <%-- 輸出當(dāng)前的聊天信息 --%> ${requestScope.chatList}
html頁面
<!DOCTYPE html> <html> <head> <meta name="author" content="Yeeku.H.Lee(CrazyIt.org)" /> <meta http-equiv="Content-Type" content="text/html; charset=GBK" /> <title>聊天頁面</title> </head> <body onload="sendEmptyRequest();"> <div style="width:780px;border:1px solid black;text-align:center"> <h3>聊天頁面</h3> <p> <textarea id="chatArea" name="chatArea" cols="90" rows="30" readonly="readonly"></textarea> </p> <div align="center"> <input id="chatMsg" name="chatMsg" type="text" size="90" onkeypress="enterHandler(event);"/> <input type="button" name="button" value="提交" onclick="sendRequest();"/> </div> </div> <script type="text/javascript"> var input = document.getElementById("chatMsg"); input.focus(); var XMLHttpReq; // 創(chuàng)建XMLHttpRequest對象 function createXMLHttpRequest() { if(window.XMLHttpRequest) { // DOM 2瀏覽器 XMLHttpReq = new XMLHttpRequest(); } else if (window.ActiveXObject) { // IE瀏覽器 try { XMLHttpReq = new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) { try { XMLHttpReq = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { } } } } // 發(fā)送請求函數(shù) function sendRequest() { // input是個全局變量,就是用戶輸入聊天信息的單行文本框 var chatMsg = input.value; // 完成XMLHttpRequest對象的初始化 createXMLHttpRequest(); // 定義發(fā)送請求的目標(biāo)URL var url = "chat.do"; // 通過open方法取得與服務(wù)器的連接 // 發(fā)送POST請求 XMLHttpReq.open("POST", url, true); // 設(shè)置請求頭-發(fā)送POST請求時需要該請求頭 XMLHttpReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); // 指定XMLHttpRequest狀態(tài)改變時的處理函數(shù) XMLHttpReq.onreadystatechange = processResponse; // 清空輸入框的內(nèi)容 input.value = ""; // 發(fā)送請求,send的參數(shù)包含許多的key-value對。 // 即以:請求參數(shù)名=請求參數(shù)值 的形式發(fā)送請求參數(shù)。 XMLHttpReq.send("chatMsg=" + chatMsg); } //定時請求服務(wù)器 function sendEmptyRequest() { // 完成XMLHttpRequest對象的初始化 createXMLHttpRequest(); // 定義發(fā)送請求的目標(biāo)URL var url = "chat.do"; // 發(fā)送POST請求 XMLHttpReq.open("POST", url, true); // 設(shè)置請求頭-發(fā)送POST請求時需要該請求頭 XMLHttpReq.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); // 指定XMLHttpRequest狀態(tài)改變時的處理函數(shù) XMLHttpReq.onreadystatechange = processResponse; // 發(fā)送請求,,不發(fā)送任何參數(shù) XMLHttpReq.send(null); // 指定0.8s之后再次發(fā)送請求 setTimeout("sendEmptyRequest()" , 800); } // 處理返回信息函數(shù) function processResponse() { // 當(dāng)XMLHttpRequest讀取服務(wù)器響應(yīng)完成 if (XMLHttpReq.readyState == 4) { // 服務(wù)器響應(yīng)正確(當(dāng)服務(wù)器響應(yīng)正確時,返回值為200的狀態(tài)碼) if (XMLHttpReq.status == 200) { // 使用chatArea多行文本域顯示服務(wù)器響應(yīng)的文本 document.getElementById("chatArea").value = XMLHttpReq.responseText; } else { // 提示頁面不正常 window.alert("您所請求的頁面有異常。"); } } } function enterHandler(event) { // 獲取用戶單擊鍵盤的“鍵值” var keyCode = event.keyCode ? event.keyCode : event.which ? event.which : event.charCode; // 如果是回車鍵 if (keyCode == 13) { sendRequest(); } } </script> </body> </html>
以上這篇Ajax解決多余刷新的兩種方法(總結(jié))就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關(guān)文章
ajax實現(xiàn)的提交文章前進(jìn)行敏感詞審核的代碼
在做“文章敏感詞匯審核”功能的時候,開始在把“審核”放在插入數(shù)據(jù)庫的時候,后來想有一個功能,能在用戶點擊“提交”按鈕的時候,給一個提示。這樣相對“友好”那么點。2010-02-02ajax+asp無限級分類樹型結(jié)構(gòu)的代碼
ajax+asp無限級分類樹型結(jié)構(gòu)的代碼...2007-10-10$.ajax中contentType: “application/json” 的用法詳解
這篇文章主要介紹了$.ajax中contentType: “application/json” 的用法,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2018-10-10ajax+springmvc實現(xiàn)C與View之間的數(shù)據(jù)交流方法
下面小編就為大家?guī)硪黄猘jax+springmvc實現(xiàn)C與View之間的數(shù)據(jù)交流方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-03-03