ajax_封装函数_步骤1

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>title</title>
</head>
<body>

</body>
</html>
<script>
  /*
    封装的过程
      重复的代码写出来
      不能固定的 作为 参数
    ajax工具函数
      回调函数的作用
  */
  // get请求
  // 因为是我们封装的函数 约定
  // data的格式是 key1=value1&key2=value2 
  function get(url,data,success){
    // 创建异步对象
    var xhr = new XMLHttpRequest();

    // 请求行
    if(data){
      url+='?';
      url+=data;
    }
    xhr.open('get',url);
    // 请求头(get可以省略)
    // 回调函数
    xhr.onreadystatechange = function(){
      if(xhr.readyState==4&&xhr.status==200){
        // 调用 传入的 回调函数
        success(xhr.responseText);
        // 普通字符串
        console.log(xhr.responseText);
        // JSON
        console.log(JSON.parse(xhr.responseText));
        // XML
        console.log(xhr.responseXML);
        // 这里用return 获取不到数据的
        // return xhr.responseText;
      }
    }
    // 请求主体 发送
    xhr.send(null);
  }

  // post请求
  function post(url,data,success){
    // 创建异步对象
    var xhr = new XMLHttpRequest();

    // 请求行
    xhr.open('post',url);

    // 请求头
    // 有数据 才要设置
    if(data){
      xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
    }
    
    // 回调函数
    xhr.onreadystatechange = function(){
      if(xhr.readyState==4&&xhr.status==200){
        console.log(xhr.responseText);
        success(xhr.responseText);
      }
    }
    
    // 请求主体 发送
    xhr.send(data);
  }

</script>
原文地址:https://www.cnblogs.com/qtbb/p/11875808.html