前端常用ajax请求整理

参考资料: 

 请求类型:

  •  xhr: https://www.w3school.com.cn/xml/xml_http.asp
  •  jquery: https://www.w3school.com.cn/jquery/ajax_ajax.asp
  •  axios:https://www.kancloud.cn/yunye/axios/234845
  •  fetch: https://developer.mozilla.org/zh-CN/docs/Web/API/Fetch_API/Using_Fet

请求头参数格式: 

  • "Content-Type", "application/x-www-form-urlencoded"    
  •  "Content-Type", "application/json" 
  •  "Content-Type", "multipart/form-data"

实例: https://gitee.com/JaggerGuo/node-express-demo

// index.js
/*
 * @Author: g05047
 * @Date: 2020-03-28 23:58:11
 * @LastEditors: g05047
 * @LastEditTime: 2020-04-08 16:10:24
 * @Description: file content
 */
const get_url = '/shopping_list';
const post_url = '/user_login';
const sql_url = 'http://localhost:8000/getAllMark';
// 请求头信息
let requestHeader = {
    'host': 'localhost:8080', //表示服务器的域名以及服务器所监听的端口号。如果所请求的端口是对应的服务的标准端口(80),则端口号可以省略
    'connection': 'keep-alive', //客户端(浏览器)想要优先使用的连接类型
    'content-length': '41',//以8进制表示的请求体的长度
    'pragma': 'no-cache', //与具体的实现相关,这些字段可能在请求/回应链中的任何时候产生。
    'cache-control': 'no-cache', //用来指定当前的请求/回复中的,是否使用缓存机制。
    'sec-fetch-mode': 'cors',
    'origin': 'http://localhost:8080', //发起一个针对跨域资源共享的请求(该请求要求服务器在响应中加入一个Access-Control-Allow-Origin的消息头,表示访问控制所允许的来源)
    'user-agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.100 Safari/537.36',//浏览器的身份标识字符串
    'content-type': 'application/json',  //请求参数类型 (用于POST和PUT请求中)
    'accept': '*/*', //浏览器能够处理的内容类型   如:text/html, image/jpeg  
    'sec-fetch-site': 'same-origin',
    'referer': 'http://localhost:8080/', //表示浏览器所访问的前一个页面,可以认为是之前访问页面的链接将浏览器带到了当前页面。Referer其实是Referrer这个单词,但RFC制作标准时给拼错了,后来也就将错就错使用Referer了。
    'accept-encoding': 'gzip, deflate, br',  //可接受的字符集
    'accept-language': 'zh-CN,zh;q=0.9', //可接受的响应内容语言列表。
    'cookie': '$Version=1; Skin=new;jsessionid=5F4771183629C9834F8382E23'
}

/***********************************************************************************************
 **************************XMLHttpRequest 的 GET 和 POST请求***********************************
 * *********************************************************************************************/

/**
 * @method: xhr_get
 * @param {type} 
 * @return: 
 */
$("#xhr_get").click(function () {
    // 1. 创建xhr对象
    let xhr = new XMLHttpRequest();
    // 2.初始化请求
    xhr.open("GET", get_url + "?userName=xiaoming", false);   // true 该请求是否异步
    // 3.发送请求
    xhr.send(null);
    // 4.监听请求的状态
    console.log('xhr_get', xhr.responseText)
    // xhr.onreadystatechange = function () {
    //     // 0: 请求未初始化 1: 服务器连接已建 2: 请求已接收 3: 请求处理中 4: 请求已完成,且响应已就绪
    //     if (xhr.readyState == 4 && xhr.status == 200) {
    //         console.log('xhr_get', xhr.responseText)
    //     }
    // }
})
/**
 * @method: xhr_post
 * @param {type} 
 * @return: 
 */
$("#xhr_post").click(function () {
    // 1. 创建xhr对象
    let xhr = new XMLHttpRequest();
    // 2.初始化请求
    xhr.open("POST", post_url, true);   // true 该请求是否异步  false 同步
    // 设置POST请求的请求头  有顺序
    // xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); //表单数据格式  表示消息内容会经过URL编码
    // 3.设置请求头
    // xhr.setRequestHeader("Content-Type", "application/json"); //json格式

    xhr.setRequestHeader("Content-Type", "multipart/form-data"); //form-data

    
    // 4.发送请求
    // xhr.send('uname=xiaoming&upwd=123456');  // 表单数据


    // xhr.send('{ "uname": "xiaoming", "upwd": "123456" }');  // json

    // form 数据
    let requestData = new FormData();
    requestData.append('uname','xiaoming');
    requestData.append('upwd','123456');

    xhr.send(requestData);
     // 5.监听请求的状态
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) { // 异步处理相对比较麻烦,要在请求状态改变事件中处理。
            // responseText    获得字符串形式的响应数据。
            // responseXML   获得XML 形式的响应数据。
            console.log('xhr_post', xhr.responseText)
        }
    }
    // 同步直接在send()后面处理返回来的数据。
    //console.log('xhr_post', xhr.responseText);
})

/***********************************************************************************************
 **************************jquery 的 GET 和 POST请求********************************************
 * *********************************************************************************************/
/**
 * @method: jquery_get1 
 * @param {type} 
 * @return: 
 */
$("#jquery_get1").click(function () {
    // 参数
    let data = { userName: 'xiaoming' }

    //方式1   $.get(URL,data,callback)
    $.get(get_url,data,(data,status,xhr)=>{
        console.log('jquery_get', data);
    })
})
/**
 * @method: jquery_get2 
 * @param {type} 
 * @return: 
 */
$("#jquery_get2").click(function () {
    // 参数
    let data = { userName: 'xiaoming' }
    // 方式2
    $.ajax({
        // 请求方式
        type: "GET",
        //请求地址
        url: get_url,
        //请求参数
        data,
        // 是否异步
        // async: true,
        //请求成功
        success: function (data) {
            console.log('jquery_get', data);
        },
        //请求失败,包含具体的错误信息
        error : function(e){
            console.log(e.status);
            console.log(e.responseText);
        }
    })
})
/**
 * @method: jquery_post1 
 * @param {type} 
 * @return: 
 */
$("#jquery_post1").click(function () {
    //  方式1   $.post(URL,data,callback);
    $.post(post_url,{uname: 'xiaoming', upwd: '123456'},function(result){
        console.log('jquery_post', result);
      });
})
/**
 * @method: jquery_post2 
 * @param {type} 
 * @return: 
 */
$("#jquery_post2").click(function () {
     // 方式2
    $.ajax({
        // 请求方式
        type: "POST",
        //请求地址
        url: post_url,
        //请求参数
        data: { uname: 'xiaoming', upwd: '123456' },
        // 是否异步
        // async: true,
        // headers:{'Content-Type':'application/json;charset=utf8'},
        //请求成功
        success: function (data) {
            console.log('jquery_post', data);
        },
         //请求失败,包含具体的错误信息
        error : function(e){
            console.log(e.status);
            console.log(e.responseText);
        }
    })
})
/***********************************************************************************************
 **************************axios 的 GET 和 POST请求********************************************
 * *********************************************************************************************/
/**
 * @method: axios_get1  发送 get 请求
 * @param {type} 
 * @return: 
 */
$("#axios_get1").click(function () {
    // 参数
    let data =  {
        userName: 'xiaoming'
    };
    // 方式1
    axios.get(get_url, {params: data}).then((response)=>{
        console.log(response);
      }).catch((error) => {
        console.log(error);
      });
})
/**
 * @method: axios_get2  发送 get 请求
 * @param {type} 
 * @return: 
 */
$("#axios_get2").click(function () {
    // 参数
    let data =  {
        userName: 'xiaoming'
    };
    
    // 方式2
    axios({
        // 请求方式
        method: 'GET',
        //请求地址
        url: get_url,
        //请求参数
        params: data
    }).then((res) => {
        // 请求成功
        console.log('axios_get', res);
    }).catch((err) => {
        // 请求失败
        console.log(err)
    });
})
/**
 * @method: axios_post1 
 * @param {type} 
 * @return: 
 */
$("#axios_post1").click(function () {
    // 请求参数
    const data = {
        uname: 'xiaoming',
        upwd: '123456'
    };

    // 方式1  axios#post(url[, data[, config]])
    axios.post(post_url, data,{
        headers: {
            'Content-Type': 'application/json;charset=utf8'
        }
    }).then((res) => {
        console.log('axios_post', res.data);
      }).catch(function (error) {
        console.log(error);
      });
})
/**
 * @method: axios_post2  
 * @param {type} 
 * @return: 
 */
$("#axios_post2").click(function () {
    // 请求参数
    const data = {
        uname: 'xiaoming',
        upwd: '123456'
    };
    // 方式2
    // 发送 POST 请求
    axios({
        headers: {
            'Content-Type': 'application/json;charset=utf8'
        }, 
        method: 'POST',
        url: post_url,
        data:JSON.stringify(data),
        // 如果请求话费了超过 `timeout` 的时间,请求将被中断
        timeout: 1000
    }).then((res) => {
          // 请求成功
        console.log('响应头', res.headers);
        console.log('axios_post', res.data);
    }).catch((err) => {
         // 请求失败
        console.log(err)
    });
})
/***********************************************************************************************
 **************************fetch 的 GET 和 POST请求********************************************
 * *********************************************************************************************/
/**
 * @method: fetch_get 
 * @param {type} 
 * @return: 
 */
$("#fetch_post").click(function () {
    let data = {
        uname: 'xiaoming',
        upwd: '123456'
    };
    // 发送 POST 请求
    fetch(post_url, {
        // 请求参数
        body: JSON.stringify(data),
        // 是否启动缓存
        cache: 'no-cache', 
        // 请求头
        headers: {
            'Content-Type': 'application/json'
        },
        // 请求方式
        method: 'POST',
    }).then(response => {
        // console.log('response',response.json());
        return  response.json();
       
    }
       ).then(res => {
        console.log('fetch_post', res);
    })
})
/**
 * @method: fetch_post 
 * @param {type} 
 * @return: 
 */
$("#fetch_get").click(function () {
    // 发送get 请求
    fetch(get_url + "?userName=xiaoming", {
        // headers: {//请求头
        //     'Content-Type': 'application/json'
        // },
        method: 'GET', // *GET, POST, PUT, DELETE, etc.
    }).then(response => response.json()).then(res => {
        console.log('fetch_get', res);
    })
})

/***********************************************************************************************
 **************************跨域********************************************
 * *********************************************************************************************/
/**
 * @method: 跨域 后台方式
 * @param {type} 
 * @return: 
 */
$("#crossOriginByBack").click(function () {
     // 方式1
     $.ajax({
        url: sql_url,
        type:'get',
        dataType: "json",  // 'json'
        success:function (data) {
            console.log('跨域',data);
        },
        error:function (err) {

        }
    });
})

/**
 * @method: jsonp 跨域 方式1
 * @param {type} 
 * @return: 
 */
$("#crossOriginByJsonp1").click(function () {
    // 方式1
    $.ajax({
        url: sql_url+1,
        type:'get',
        dataType: "jsonp",  // 'json'
        success:function (data) {
            console.log('jsonp',data);
        },
        error:function (err) {

        }
    });
})
/**
 * @method: jsonp 跨域 方式2
 * @param {type} 
 * @return: 
 */
$("#crossOriginByJsonp2").click(function () {
    // 方式2
    $.getJSON(sql_url+1+ "?callback=?", function(data) {
        console.log('jsonp',data);
    });
})

/**
 * @method: jsonp 跨域 方式3 script标签方式
 * @param {type} 
 * @return: 
 */
// 调用传递回来的方法 获取数据
function dataS(dt) {
    console.log('jsonp script', dt)
}
$("#crossOriginByJsonp3").click(()=>{
     // 方式3
     function addScript(url) {
        // 创建一个script标签
        var scpt = document.createElement('script');
        // 设置对应的src
        scpt.src = url;
        // 追加到页面
        document.body.appendChild(scpt);
    }
    addScript('http://localhost:8000/getAllMark/callback=dataS')
})

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值