006_Ajax发送POST请求
生活随笔
收集整理的這篇文章主要介紹了
006_Ajax发送POST请求
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1. 使用我們的Ajax動態WEB項目
2. 編寫ajax_post.html
<!DOCTYPE html> <html><head><meta charset="utf-8" /><title>Ajax post請求獲取字符串響應</title></head><body> <form action="" method="post">用戶名: <input type="text" name="userName" autofocus="autofocus" onBlur="showHint(this.value)" /><span id="txtHint"></span><br />密碼: <input type="password" name="password" /><br /><input type="submit" value="提交" /></form><script type="text/javascript">function showHint(userName){if(userName == undefined){document.getElementById("txtHint").innerHTML="請輸入用戶名";return;}// 創建XMLHttpRequest對象。XMLHttpRequest對象用于和服務器交換數據。var xmlHttp = new XMLHttpRequest();xmlHttp.onreadystatechange = function(){// 4請求完成, 200服務器返回狀態OK。if(xmlHttp.readyState == 4 && xmlHttp.status == 200){// 獲取字符串響應document.getElementById("txtHint").innerHTML=xmlHttp.responseText;}}// 使用XMLHttpRequest對象的open()和send()方法, 發送post請求到服務器。xmlHttp.open("post", "register.action", true);xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded; charset=UTF-8");xmlHttp.send("userName="+encodeURIComponent(userName));}</script></body> </html>3. 編寫RegisterAction.java
package com.lywgames.ajax;import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse;public class RegisterAction extends HttpServlet {private static final long serialVersionUID = 1L;@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {String userName = req.getParameter("userName");String result = "";if("zhangsan".equals(userName) || "lisi".equals(userName)) {result = "用戶名已注冊";}if(null == userName || userName.length() < 3) {result = "用戶名不合法";}// 響應客戶端的內容類型是text/html 編碼是UTF-8(包含字符編碼和網頁編碼)resp.setContentType("text/html;charset=UTF-8");resp.getWriter().write(result);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req, resp);} }4. 配置web.xml
5. 運行項目, 輸入用戶名lisi, 失去焦點
?
總結
以上是生活随笔為你收集整理的006_Ajax发送POST请求的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 005_Ajax get请求获取XML响
- 下一篇: 010_jQuery获取和设置内容属性