H5 html单页面实现对接接口,获取接口数据

一、AJAX的一种实现方式,XMLHttpRequest

var xhr = new XMLHttpRequest();  
xhr.open("POST", "你的接口URL", true);  
xhr.setRequestHeader("Content-Type", "application/json;charset=UTF-8");  
  
// 准备发送的数据  
var data = JSON.stringify({  
    key1: "value1",  
    key2: "value2"  
});  
  
xhr.onreadystatechange = function () {  
    if (xhr.readyState == 4 && xhr.status == 200) {  
        // 请求成功,处理响应数据  
        console.log(xhr.responseText);  
    }  
};  
  
xhr.send(data);

二、fetch API来发送POST请求并携带body参数(通常是JSON格式的数据)是一种常见的做法,

注意:

fetch 调用内部的 .then() 方法中执行的,因此它只能在 fetch 请求成功完成并且响应数据被解析为 JSON 后才能访问到 data ,这意味着 data 变量在 fetch 调用外部是不可直接访问的,因为它在异步操作完成之前还不存在。

<script>    
    fetch('你的接口URL', {  
        method: 'POST', // 设置请求方法为POST  
        headers: {  
            'Content-Type': 'application/json', // 设置请求头,指明发送的信息类型为JSON  
            // 如果需要,可以在这里添加其他请求头,比如认证信息  
            // 'token': 'Bearer your_token_here'  
        },  
        body: JSON.stringify(postData) // 将JavaScript对象转换为JSON字符串,并作为请求体发送  
    })  
    .then(response => {  
        // 检查响应是否成功  
        if (!response.ok) {  
            throw new Error('Network response was not ok');  
        }  
        return response.json(); // 解析JSON响应数据  
    })  
    .then(data => {  
        console.log('Success:', data); // 处理响应数据  
    })  
    .catch(error => {  
        console.error('There was a problem with your fetch operation:', error);  
        // 在这里处理错误,比如显示错误消息给用户  
    });  
</script> 

 

posted @ 2024-08-13 11:51  danmo_xx  阅读(56)  评论(0编辑  收藏  举报