zoukankan      html  css  js  c++  java
  • 原生js实现Ajax请求,包含get和post

    现在web从服务器请求数据,很多用到Ajax,不过都是用的JQuery封装好的,之前做项目,由于无法引用JQuery,所以就只能用原生了,话不多说,请看代码。

     1 /*-------------------Ajax start--------------------*/
     2 
     3 function ajax(options) {
     4     options = options || {};
     5     options.type = (options.type || "GET").toUpperCase();
     6     options.dataType = options.dataType || "json";
     7     var params = formatParams(options.data);
     8     var xhr;
     9  
    10     //创建 - 第一步
    11     if (window.XMLHttpRequest) {
    12       xhr = new XMLHttpRequest();
    13     } else if(window.ActiveObject) {         //IE6及以下
    14       xhr = new ActiveXObject('Microsoft.XMLHTTP');
    15     }
    16  
    17     //连接 和 发送 - 第二步
    18     if (options.type == "GET") {
    19       xhr.open("GET", options.url + "?" + params, true);
    20       xhr.send(null);
    21     } else if (options.type == "POST") {
    22       xhr.open("POST", options.url, true);
    23       //设置表单提交时的内容类型
    24       xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    25       xhr.send(params);
    26     }
    27 
    28      //接收 - 第三步
    29     xhr.onreadystatechange = function () {
    30       if (xhr.readyState == 4) {
    31         var status = xhr.status;
    32         if (status >= 200 && status < 300 || status == 304) {
    33           options.success && options.success(xhr.responseText, xhr.responseXML);
    34         } else {
    35           options.error && options.error(status);
    36         }
    37       }
    38     }
    39   }
    40 
    41 //格式化参数
    42 function formatParams(data){
    43     var arr = [];
    44     for (var name in data) {
    45       arr.push(encodeURIComponent(name) + "=" + encodeURIComponent(data[name]));
    46     }
    47     arr.push(("v=" + Math.random()).replace(".",""));
    48     return arr.join("&");
    49 }
    50 
    51 /*-------------------Ajax end-------------------*/

    自己封装Ajax,主要分三步:

    第一步:创建需要的对象,这里主要用到的是XMLHttpRequest,注意需要考虑早期的IE;

    第二步:连接和发送;

    第三步:接收;

    这里为了格式化请求参数,封装了一个formatParams(data)函数。

  • 相关阅读:
    461. Hamming Distance
    342. Power of Four
    326. Power of Three
    368. Largest Divisible Subset java solutions
    95. Unique Binary Search Trees II java solutions
    303. Range Sum Query
    160. Intersection of Two Linked Lists java solutions
    88. Merge Sorted Array java solutions
    67. Add Binary java solutions
    14. Longest Common Prefix java solutions
  • 原文地址:https://www.cnblogs.com/lanyueboyu/p/8793352.html
Copyright © 2011-2022 走看看