Ajax 原生

52 阅读1分钟
      /**
       * 使用window上原声对象,XMLHttpRequest方法
       * get 请求方式
       * */
      function ajaxGet() {
        let data = [];
        // 创建ajax对象
        let xhr = new XMLHttpRequest();
        // 配置请求方式和请求地址
        xhr.open('get', '请求地址?name=请求参数');
        // 发送请求
        xhr.send();
        //监听请求状态,并接受响应数据
        xhr.onreadystatechange = function () {
          if (xhr.readyState === 4 && xhr.status === 200) {
            // 响应后的数据是一个JSON字符串,所以需要转译
            data = JSON.parse(xhr.responseText);
          }
        };
        return data;
      }

      /**
       * post 请求方式
       * post 需要设置请求头
       * post 请求的参数是写在发送send()里
       */
      function ajaxPost() {
        const datas = [];
        // 创建ajax对象
        let xhr = new XMLHttpRequest();
        // 配置请求方式和请求地址
        xhr.open('post', '请求地址');
        // 配置请求头 (form - 表单数据格式提交)(json - json数据格式提交)
        xhr.setRequestHeader('content-type', 'application/x-www-form-urlencoded');
        // xhr.setRequestHeader('content-type', 'application/json');
        // 发送请求
        xhr.send('请求参数');
        // 监听请求状态,并响应接收数据
        xhr.onreadystatechange = function () {
          if (xhr.readyState === 4 && xhr.status === 200) {
            datas = xhr.responseText;
          }
        };
        return datas;
      }