首页 > 其他分享 >jQuery中发起 ajax 请求,自己封装get请求

jQuery中发起 ajax 请求,自己封装get请求

时间:2022-09-27 15:24:23浏览次数:53  
标签:jQuery 请求 get url res xhr key

jQuery中发起 ajax 请求

参数:1.请求地址    2.参数    3.回调函数(参数为响应数据)

//get请求参数拼接到url中
$.get("http//127.0.0.1:8000", { a: 100, b: 200 }, (res) => {
  console.log(res);
});
//post请求参数携带在请求体中
$.post("http//127.0.0.1:8000", { a: 100, b: 200 }, (res) => {
  console.log(res);
});

通用方式

传入一个对象,指定请求地址、参数、请求方法、回调函数等

$.ajax({
  url: "http://127.0.0.1:88e0/jquery-server", // 请求地址url
  data: { a: 100, b: 200 }, //参数
  type: "GET", //请求方法
  //成功的回调
  success: function (res) {
    console.log(res);
  },
});

此外还可以设置 请求头、响应数据的格式、超时时间、失败的回调函数等

$.ajax({
  url: "http://127.0.0.1:88e0/jquery-server", // 请求地址url
  data: { a: 100, b: 200 }, //参数
  type: "GET", //请求方法
  dataType: "json", //会自动序列化响应的数据
  //成功的回调
  success: function (res) {
    console.log(res);
  },
  timeout: "2000", //超时时间
  //错误的回调,网络错误、请求超时等
  error: function () {
    console.log("出错了!");
  },
  //设置请求头
  header: {
    a: 100,
    b: 200,
  },
});

get请求封装

//封装get请求 请求地址  请求的参数  回调函数
static get(url,param={},callback){
    if(!url){
        throw new Error('url地址必须要填入')
    }
    //参数解析 ?key=value&key1=value1
    // 遍历param对象
    for(let key in param){
        //url里面如果存在?
        if(url.includes('?')){
            url += `&${key}=${param[key]}`
        }else{
            url += `?${key}=${param[key]}`
        }
    }
    let xhr = new XMLHttpRequest() || new ActiveXObject("Microsoft.XMLHTTP")
    xhr.open('get',url)
    xhr.send()
    xhr.onreadystatechange = function(){
        if(xhr.readyState == 4 && /^2\d{2}$/.test(xhr.status)){
            let response = JSON.parse(xhr.responseText)
            if(callback instanceof Function){
                callback(response)
            }
        }
    }
}

标签:jQuery,请求,get,url,res,xhr,key
From: https://www.cnblogs.com/qianduanLamp/p/16734658.html

相关文章