zoukankan      html  css  js  c++  java
  • 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>
  • 相关阅读:
    初学JS——利用JS制作的别踩白块儿(街机模式) 小游戏
    对于大数据量的Json解析
    Json数据中的特殊字符处理
    移动端总结和手机兼容问题
    在DW 5.5+PhoneGap+Jquery Mobile下搭建移动开发环境
    HTML5所有标签汇总
    二叉树
    二分查找
    归并排序
    希尔排序
  • 原文地址:https://www.cnblogs.com/qtbb/p/11875808.html
Copyright © 2011-2022 走看看