原生js實現ajax

來源:互聯網
上載者:User

標籤:push   .com   發送   ase   核心   cat   log   view   activex   

自從javascript有了各種架構之後,比如jquery,使用ajax已經變的相當簡單了。但是有的項目不需要載入jquery這種龐大的js外掛程式,只需要實現ajax即可。所以我們就需要自己用原生JS實現ajax

ajax:一種請求資料的方式,不需要重新整理整個頁面;

ajax的技術核心是 XMLHttpRequest 對象;

ajax 請求過程:建立 XMLHttpRequest 對象、串連伺服器、發送請求、接收響應資料;

<script type="text/javascript"> function ajax(opt) {       opt = opt || {};       opt.method = opt.method.toUpperCase() || ‘POST‘;        opt.url = opt.url || ‘‘;       opt.async = opt.async || true;        opt.data = opt.data || null;        opt.success = opt.success || function () {};        var xmlHttp = null;        if (XMLHttpRequest) {          xmlHttp = new XMLHttpRequest();        }        else {           xmlHttp = new ActiveXObject(‘Microsoft.XMLHTTP‘);        } var params = [];        for (var key in opt.data){            params.push(key + ‘=‘ + opt.data[key]);        }       var postData = params.join(‘&‘);        if (opt.method.toUpperCase() === ‘POST‘) {           xmlHttp.open(opt.method, opt.url, opt.async);            xmlHttp.setRequestHeader(‘Content-Type‘, ‘application/x-www-form-urlencoded;charset=utf-8‘);            xmlHttp.send(postData);        }       else if (opt.method.toUpperCase() === ‘GET‘) {            xmlHttp.open(opt.method, opt.url + ‘?‘ + postData, opt.async);             xmlHttp.send(null);        }         xmlHttp.onreadystatechange = function () {           if (xmlHttp.readyState == 4 && xmlHttp.status == 200) {                opt.success(xmlHttp.responseText);            }         };    }</script>

  樣本:

<script>ajax({     method: ‘POST‘,     url: ‘login.php‘,     data: {       code:‘p001‘,name:‘李四‘     },    success: function (response) {       console.log(response);    } })</script>

  

原生js實現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.