JQ 的 AJAX 请求方法

$.ajax() 基础方法

$.ajax() 是 jQuery 中最底层的 AJAX 实现,支持高度自定义配置:

javascript 复制代码
$.ajax({
  url: "https://api.example.com/data",
  type: "GET", // 或 "POST"
  dataType: "json", // 预期返回的数据类型
  data: { key1: "value1", key2: "value2" }, // 发送的数据
  success: function(response) {
    console.log("请求成功:", response);
  },
  error: function(xhr, status, error) {
    console.error("请求失败:", status, error);
  }
});

快捷方法

jQuery 提供了更简洁的快捷方法:

GET 请求

javascript 复制代码
$.get("https://api.example.com/data", { param1: "value1" }, function(response) {
  console.log("GET 响应:", response);
}, "json");

POST 请求

javascript 复制代码
$.post("https://api.example.com/submit", { name: "John", age: 30 }, function(response) {
  console.log("POST 响应:", response);
});

加载 HTML 片段

javascript 复制代码
$("#result").load("partial.html #content"); // 加载指定元素的片段

处理 JSON 数据

获取 JSON 数据

javascript 复制代码
$.getJSON("https://api.example.com/users", function(data) {
  $.each(data, function(index, user) {
    console.log(user.name);
  });
});

提交 JSON 数据

javascript 复制代码
$.ajax({
  url: "https://api.example.com/save",
  type: "POST",
  contentType: "application/json",
  data: JSON.stringify({ id: 1, name: "Alice" }),
  success: function(response) {
    console.log("保存成功");
  }
});
全局事件处理

jQuery 允许绑定全局 AJAX 事件:

javascript 复制代码
$(document).ajaxStart(function() {
  $("#loading").show();
}).ajaxStop(function() {
  $("#loading").hide();
});
跨域请求 (CORS)

对于跨域请求,确保服务器支持 CORS:

javascript 复制代码
$.ajax({
  url: "https://other-domain.com/api",
  crossDomain: true,
  xhrFields: {
    withCredentials: true // 需要时发送凭据
  }
});

使用 Promises

jQuery AJAX 返回的是 jqXHR 对象,支持 Promise 语法:

javascript 复制代码
$.get("https://api.example.com/data")
  .done(function(data) {
    console.log("成功:", data);
  })
  .fail(function(xhr, status) {
    console.error("失败:", status);
  });
相关推荐
夜郎king21 小时前
湖南高考天气查询:基于 HTML5 与百度天气 API 实现页面展示
前端·html5·百度天气实践·天气信息可视化
云水一下1 天前
TypeScript 从零基础到精通(五):高级类型与泛型
前端·javascript·typescript
counterxing1 天前
vibe coding 之后,我更不想打字了
前端·agent·ai编程
copyer_xyf1 天前
Python 模块与包的导入导出
前端·后端·python
研☆香1 天前
es6新特性功能介绍(四)
前端·ecmascript·es6
微扬嘴角1 天前
React篇1--JSX语法规则、组件、组件实例的3大特性
前端·react.js·前端框架
copyer_xyf1 天前
Python venv 虚拟环境
前端·后端·python
无聊的老谢1 天前
Vue 3 + TypeScript 构建大型电信运维平台的前端架构设计
前端·vue.js·typescript
xiaofeichaichai1 天前
Map / Set / WeakMap / WeakSet
前端·javascript
李可以量化1 天前
成交量的终极量化策略:价量共振指标完整实现(下篇)
前端·数据库·人工智能