当前位置:首页 > 行业动态 > 正文

html怎么调用api接口

使用Fetch或XMLHttpRequest发送请求,处理响应数据

HTML调用API接口的实现方式

HTML本身是静态标记语言,无法直接发起网络请求,需结合JavaScript实现API调用,以下是具体实现步骤:

html怎么调用api接口  第1张

使用fetch方法(现代浏览器推荐)

// 示例:调用JSONPlaceholder的GET接口
fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then(response => response.json())  // 解析JSON响应
  .then(data => {
    console.log(data);                // 处理数据
    document.getElementById('result').innerText = JSON.stringify(data); // 显示在页面
  })
  .catch(error => console.error('Error:', error)); // 错误处理

使用XMLHttpRequest(兼容旧浏览器)

// 示例:POST请求发送JSON数据
var xhr = new XMLHttpRequest();
xhr.open('POST', 'https://jsonplaceholder.typicode.com/posts');
xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
xhr.onreadystatechange = function() {
  if (xhr.readyState === 4) {
    if (xhr.status === 201) {
      console.log(JSON.parse(xhr.responseText)); // 处理成功响应
    } else {
      console.error('Error:', xhr.statusText);
    }
  }
};
xhr.send(JSON.stringify({ title: 'foo', body: 'bar', userId: 1 }));

关键参数说明表

参数名称 作用描述
method HTTP方法(GET/POST/PUT/DELETE等)
headers 设置请求头(如Content-Type: application/json
body POST/PUT请求的请求体(需字符串化)
.then() 处理Promise成功回调(fetch专用)
.catch() 捕获网络错误或解析错误(fetch专用)
onreadystatechange 监听请求状态变化(XMLHttpRequest专用)
response.json() 将响应流解析为JSON对象(需在.then()中调用)

fetch与XMLHttpRequest对比

特性 fetch XMLHttpRequest
语法复杂度 简洁(链式调用) 冗长(需手动处理状态变化)
返回值类型 Promise对象 无(需通过事件监听获取结果)
兼容性 IE11+(需polyfill支持旧浏览器) 全平台支持
错误处理 .catch()统一处理 需判断statusreadyState
流式处理 支持流式读取(如response.text() 需手动处理responseText/responseXML

常见问题与解答

问题1:如何处理跨域请求?
解答:需API服务端设置Access-Control-Allow-Origin响应头,浏览器会阻止未授权的跨域请求,若遇到CORS错误,需联系API提供方开启跨域支持,或通过服务器代理转发请求。

问题2:如何传递查询参数(如?id=123)?
解答:

  • GET请求:直接拼接URL,
    fetch(`https://api.example.com/data?id=${encodeURIComponent(123)}`)
  • POST请求:将参数放入body
    fetch('https://api.example.com/data', {
      method: 'POST',
      body: JSON.stringify({ id: 123 }),
      headers: { 'Content-Type': 'application/json' }
    });
0