1. 程式人生 > >JS實現非同步提交

JS實現非同步提交

  • 什麼是XMLHttpRequest?
    • XMLHttpRequest物件用於在後臺與伺服器交換資料
  • XMLHttpRequst的作用
    • 在不重新載入頁面的情況下更新網頁 
    • 在頁面已載入後從伺服器請求資料
    • 在頁面已載入後從伺服器接收資料
    • 在後臺向伺服器傳送資料
  • 若出現Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED.
    • 設定請求頭必須在open開啟之後,send之前
  • JS實現非同步提交
    <!--
    onchange觸發事件必須滿足兩個條件:
    (1)當前物件屬性發生改變
    (2)當前物件失去焦點
    -->
    <input type="text" name="username" id="username" placeholder="請輸入使用者名稱" >



    var username = document.getElementById("username");
    /**
    * 獲取XMLHttpRequestObject物件
    */
    function getXMLHttpRequestObject(url, param) {
    //建立XMLHttpRequest物件
    var xmlhttp;
    //為了應對所有現代瀏覽器,檢查是否支援XMLHttpRequst,若支援則建立XMLHttpRequest物件,若不支援,則建立ActiveXObject物件
    if (window.XMLHttpRequest) {
    xmlhttp = new XMLHttpRequest();

    } else {
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    //規定請求的型別、URL、是否非同步請求
    xmlhttp.open('get', url + '?' + param, true);
    //新增請求頭必須在open開啟之後,send之前
    //想請求新增Http請求頭
    xmlhttp.setRequestHeader("Context-type", "application/x-www-form-urlencoded");
    //將請求傳送到伺服器
    xmlhttp.send();

    return xmlhttp;
    }
     
       
    /**
    * 驗證使用者名稱
    */
    username.onchange = function () {

    var usernameValue = username.value;
    var param = "username=" + usernameValue
    var url = "/register";
    var xmlhttp = getXMLHttpRequestObject(url, param);
    //設定監聽函式,若為true時,在事件中的就緒狀態時執行函式
    xmlhttp.onreadystatechange = function () {
    //判斷請求是否成功,每當readyState屬性改變時,就會呼叫該函式
    //readyState的狀態:0(請求未初始化)、1(伺服器連線已建立)、2(請求已接收)、3(請求處理中)、4(請求已完成,且響應已就緒)
    //status的狀態:200(ok),404(未找到頁面)
    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {

    //獲取伺服器的響應,通過
    //responseText:獲取字串形式的響應資料
    //responseXML:獲取XML形式的響應資料
    console.log(xmlhttp.responseText);
    }
    }

    }



    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    String username = req.getParameter("username");
    resp.setContentType("text/html;charset=utf-8");
    PrintWriter out = resp.getWriter();
    out.println("我已經收到你的來信了");
    }