Ajax發送Post請求

來源:互聯網
上載者:User

標籤:ajax   post   

Ajax發送post請求與發送get請求大致類似,下面看具體執行個體,首先看JSP顯示頁面:

<form action="servlet/LoginServlet" method="post">    <table>    <tr>    <td>使用者帳號:</td>    <td><input type="text" name="username" onblur="checkUser(this)"/></td>    </tr>    <tr>    <td>使用者密碼:</td>    <td><input type="password" name="password"/></td>    </tr>    <tr>    <td><input type="submit" value="註冊"/></td>    <td><input type="reset" value="重設"></td>    </tr>    </table>    </form>
然後看對發送資訊進行處理的Servlet類,因為是POST方式發送資訊,所以看一下doPost方法。

@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {response.setContentType("text/html;charaet=UTF-8");PrintWriter out = response.getWriter();String name=request.getParameter("username");if(name.equals("admin"))out.print(false);elseout.print(true);out.flush();out.close();}

然後看javascript如何?Ajax請求

<script type="text/javascript">//建立XMLHttpRequestfunction createXmlHttpRequest(){if(window.XMLHttpRequest){return new XMLHttpRequest();}else{return new ActiveXObject("Microsoft.XMLHTTP");}}//當使用者帳號輸入框失去焦點時調用該方法function checkUser(obj){//擷取輸入框輸入的值var user = obj.value;//如果輸入框中的值為空白,那麼彈窗提示,並且讓該輸入框獲得焦點if(!user){alert("使用者名稱不可為空!");obj.focus();return;}//不為空白時,使用Ajax請求向後台發送資訊,驗證該使用者名稱是否可用//post請求字串var url="servlet/LoginServlet";//請求參數var userinfo = "username="+user;//調用方法建立XMLHttpRequest對象XmlHttpRequest = createXmlHttpRequest();//設定回呼函數XmlHttpRequest.onreadystatechange=finish;//初始化xmlhttprequestXmlHttpRequest.open("POST",url,true);XmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");//發送請求XmlHttpRequest.send(userinfo);}//回呼函數function finish(){if(XmlHttpRequest.readyState == 4&& XmlHttpRequest.status == 200){var result = XmlHttpRequest.responseText;alert(result);if(result =="true"){alert("使用者名稱可用!");}else{alert("使用者名稱不可用!");}}}</script>


Ajax發送Post請求

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.