以下是一个使用jQuery的例子,向后端API发送GET请求,并在成功响应时更新页面上的元素:

HTML:

<div id="result"></div>

JavaScript:

$(document).ready(function() {
  $.ajax({
    type: "GET",
    url: "https://example.com/api",
    dataType: "json",
    success: function(data) {
      $("#result").html(data.message);
    },
    error: function(xhr, status, error) {
      console.log(error);
    }
  });
});

解释:

  • $(document).ready(function() { ... }); 确保当页面加载时,JavaScript代码被执行。
  • $.ajax({ ... }); 发送一个AJAX请求。参数包括请求类型(GET/POST),URL和成功/失败处理函数。
  • dataType: "json" 指定响应类型为JSON。
  • success: function(data) { ... } 当请求成功时,执行该函数。data变量包含从API返回的JSON数据。
  • $("#result").html(data.message); 更新页面上ID为result的元素的内容为从API返回的消息。
  • error: function(xhr, status, error) { ... } 当请求失败时,执行该函数。xhr变量包含XMLHttpRequest对象,status变量包含错误状态(如404),error变量包含错误消息。在这个例子中,我们只是把错误消息打印到控制台上
给个可以运行的例子ajax请求后端的接口

原文地址: https://www.cveoy.top/t/topic/fVdj 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录