zoukankan      html  css  js  c++  java
  • javascript

    封装,使用有示例.

     1     // 封装示例:
     2     function ajax(url, method, params, done) {
     3       var xhr = null;
     4       method = method.toUpperCase();
     5       xhr = window.XMLHttpRequest ? xhr = window.XMLHttpRequest : xhr = new ActiveXObject('Microsoft.XMLHTTP');
     6 
     7       if (typeof params === 'object') {
     8         var tempArr = [];
     9         for (var key in params) {
    10           var value = params[key];
    11           tempArr.push(key + '=' + value);
    12         }
    13         params = tempArr.join('&');
    14       }
    15 
    16       // GET
    17       if (method === 'GET') {
    18         url += '?' + params;
    19       }
    20       xhr.open(method, url, false);
    21 
    22       // POST
    23       var data = null;
    24       if (method === 'POST') {
    25         xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    26         data = params;
    27       }
    28 
    29       xhr.onreadystatechange = function () {
    30         if (this.readyState !== 4 && this.status !== 200) return false;
    31         ongone(this.responseText);
    32       }
    33       xhr.send(data);
    34     }
    35 
    36 
    37     // 调用示例:ajax('get','test.php',{id:123,},ongone)
    38     ajax('GET', 'test.php', {}, ongone);
    39 
    40     var ongone = function (res) {
    41       console.log('1');
    42       console.log('2');
    43       console.log(res);
    44       console.log('gone!');
    45     }
  • 相关阅读:
    Java第一次作业
    第十一次作业
    第十次作业
    第九次作业
    第八次作业
    第七次作业
    第六次作业
    第五次作业
    java第三次实验
    java 第二次实验
  • 原文地址:https://www.cnblogs.com/cisum/p/9379319.html
Copyright © 2011-2022 走看看