• 原生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)函数。

  • 相关阅读:
    高性能 HTML5 地铁样式的应用程序中的内容
    微软披露更多ARM Win8细节
    下一代互联网搜索的前沿:意图、知识与云
    使用 Sphinx 更好地进行 MySQL 搜索使用 Sphinx 进行非全文本搜索
    如何加快数模计算以及如何解决数模计算的收敛性问题
    Google App Engine正式支持Python 2.7
    ASP.NET MVC模型绑定
    给 MySQL 增加 Sequence 管理功能
    使用 Rational Build Forge 自动化 IBM Cloud 上的构建和发布过程
    Windows Phone 8基于WinRT?
  • 原文地址:https://www.cnblogs.com/lanyueboyu/p/8793352.html
Copyright © 2020-2023  润新知