码迷,mamicode.com
首页 > Web开发 > 详细

ajax_封装函数_步骤1

时间:2019-11-17 13:12:32      阅读:91      评论:0      收藏:0      [点我收藏+]

标签:encode   log   oct   val   请求   htm   ati   class   script   

<!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>

 

ajax_封装函数_步骤1

标签:encode   log   oct   val   请求   htm   ati   class   script   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!