• 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>
  • 相关阅读:
    计算机中最重要的两个硬件是什么它们如何相互作用。
    音乐光盘
    下列各项包含多少位?
    下列包含多少字节?
    自测题‘
    自测题.
    python 并发编程多线程之进程池/线程池
    python 并发编程之多线程
    基于解决高并发生的产者消费者模型
    守护进程、互斥锁、进程间通信(IPC机制)
  • 原文地址:https://www.cnblogs.com/qtbb/p/11875808.html
Copyright © 2020-2023  润新知