ajax發送非同步請求

來源:互聯網
上載者:User

標籤:jsp   mic   5.5   win   write   load   ati   sign   input   

一:得到XMLHttpRequest對象

  ajax其實只需要學習XMLHttpRequest一個對象

  大多數瀏覽器都支援:  

var xmlHttp = new XMLHttprequest();

  IE 6.0:

var mltHttp = new ActiveXObject("Msxml2.XMLHTTP");

  IE 5.5 及更早的IE

var xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");

    * 編寫建立XMLHttpRequest對象函數  

function createXMLHttpRequest(){            try{           return  new XMLHttpRequest();     }catch(e){            try{                  return new ActiveXObject("Msxml2.XMLHTTP");           }catch(e){                    try{                            return new ActiveXObject(Microsoft.XMLHTTP‘);                     }catch(e){                           throw e;                   }          }    }}                                    

二:開啟與伺服器的連結

  xmlHttp.open()用來開啟與伺服器的連結

  參數:請求方式,請求URL,請求是否為非同步

xmlHttp.oprn("GET","/AServlet",true);

三:發送請求 

xmlHttp.send(null);//如果不寫null可能導致部分瀏覽器無法使用

GET請求必須寫null

四:

  要在xmlHttp對象的一個事件上註冊監聽器:onreadystatechange

  得到xmlHttp對象的狀態:

var state = xmlHttp.readyState;//可能是0、1、2、3、4

  得到伺服器響應的狀態代碼

var status = xmlHttp.status;//例如200、404、500

  得到伺服器響應的內容

var content = xmlHttp.responseText;//得到伺服器響應的文字格式設定的內容var content = xmlHttp.responseXML;//得到伺服器響應的XML響應內容,它是Document對象了
xmlHttp.onreadystatechange = function(){//xmlHttp的5種狀態都會調用本方法    if(xmlHttp.readyState ==4 && xmlHttp.status ==200){//雙重判斷,既要響應成功,又要伺服器響應結束    //擷取伺服器響應的內容        var text = xmlHttp.responseText;    }};

五:POST(如果發送請求時帶有參數,一般使用POST請求)

  open :

xmlHttp.open("POST");

  添加一步:設定Content-Type要求標頭

xmlHttp.setRequestHeander("Content-Type","application/x-www-form-urlencoded");

  send:

xmlHttp.send("username=xxx&password=xxx");

jsp

<%--  Created by IntelliJ IDEA.  User: YuWenHui  Date: 2017/4/20 0020  Time: 19:12  To change this template use File | Settings | File Templates.--%><%@ page contentType="text/html;charset=UTF-8" language="java" %><%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><html>  <head>    <title>AJAX</title>      <script type="text/javascript">          function createXMLHttpRequest() {              try {                    return new XMLHttpRequest();              }catch (e){                  try {                         return new ActiveXObject("Msxml2.XMLHTTP");                  }catch (e){                      try {                            return new ActiveXObject("Microsoft.XMLHTTP");                      }catch (e){                            throw e;                      }                  }              }          }          window.onload = function () {              var username = document.getElementsByName("username");              username.onblur=function () {                  var xmlHttp = createXMLHttpRequest();                  xmlHttp.open("POST","<c:url value=‘/ValidateUsenameServlet‘/> ",true);                  xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");                  xmlHttp.send("username="+username.value);                  xmlHttp.onreadystatechange=function () {                      if(xmlHttp.readyState==4 && xmlHttp.status ==200){                          var span = document.getElementsByName("errorSpan");                          if(xmlHttp.responseText == 1){                             span.innerHTML="該使用者名稱已被註冊";                          }else {                              span.innerHTML="";                          }                      }                  }              }          }      </script>  </head>  <body>    <h1>測試使用者名稱是否被註冊</h1>    <form action="" method="post">        使用者名稱:<input type="text" name="username" ><span name="errorSpan"></span><br/>        密  碼:<input type="password" name="password"><br>        <input type="submit" value="登陸">    </form>  </body></html>

sevlet

package servlet;import java.io.IOException;/** * Created by YuWenHui on 2017/4/20 0020. */public class ValidateUsenameServlet extends javax.servlet.http.HttpServlet {    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {        response.setContentType("text/html;charset=utf-8");        request.setCharacterEncoding("utf-8");        String name = request.getParameter("username");        if ("yuwenhui".equalsIgnoreCase(name) && "餘文輝".equalsIgnoreCase(name)){            response.getWriter().print("1");        }else {            response.getWriter().print("0");        }    }}

 

ajax發送非同步請求

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.