JS构建请求(get/post)

JS构建请求(get/post)


Fetch用法


get请求


function GetData(){
    fetch('/GetData')
        .then(response => {
            if (response.ok){return response.json()}
        })
        .then(data => console.log(data))
        .catch(error => console.error('Fetch error:', error));
};


post请求


function GetTimet(){
    // 发起 POST 请求
    fetch('/GetTime', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({ key1: 'value1',key2: 'value2'}) })
        .then(response => response.json())
        .then(data => console.log(data))
        .catch(error => console.error('Fetch error:', error));
}


XMLHttpRequest用法


get请求


function GetMessages_() {
    var xhr = new XMLHttpRequest();
    xhr.open("GET", "/getmessage", true); // 这里的 "/get_messages" 是 后端接口地址
    xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
    // 处理请求完成时的回调
    xhr.onload = function () {
        if (xhr.status === 200) {
            // 请求成功,你可以在这里处理成功的情况
            state=JSON.parse(xhr.responseText);
        } else {
            // 请求失败,你可以在这里处理失败的情况
            console.error("数据获取失败");
        }
    };
    // 处理请求发生错误时的回调
    xhr.onerror = function () {console.error("请求发生错误");};
    // 发送 JSON 格式的数据
    xhr.send();
}


post请求


function run_() {
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "/run", true); // 这里的 "/get_datas" 是后端接口地址
    xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
    var options=[option1.checked,option2.checked,option3.checked,option4.checked,option5.checked,option6.checked]
    datas={ "name": name_.textContent,"phone":phone_.textContent,"options":options}
    // 处理请求完成时的回调
    xhr.onload = function () {
        if (xhr.status === 200) { // 请求成功,你可以在这里处理成功的情况
            state=JSON.parse(xhr.responseText);               
        } else { // 请求失败,你可以在这里处理失败的情况
            console.error("数据获取失败");}};
    // 处理请求发生错误时的回调
    xhr.onerror = function () { console.error("请求发生错误"); };
    // 发送 JSON 格式的数据
    xhr.send(JSON.stringify(datas));
}


 

  • 10
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值