jQuery $.ajax() 方法详解

jQuery $.ajax() 方法详解

$.ajax() 是 jQuery 提供的一个方法,用于执行异步 HTTP(Ajax)请求。它是 jQuery 最强大的方法之一,允许你通过配置选项来执行各种类型的请求,并处理响应数据。

基本用法

$.ajax({
    url: 'your-url',        // 请求的 URL
    type: 'GET',            // 请求类型 (GET, POST, PUT, DELETE, etc.)
    dataType: 'json',       // 预期服务器返回的数据类型 (json, xml, html, text)
    data: {                 // 发送到服务器的数据 (可以是对象或字符串)
        key1: 'value1',
        key2: 'value2'
    },
    success: function(response) {  // 请求成功的回调函数
        console.log('成功:', response);
    },
    error: function(xhr, status, error) {  // 请求失败的回调函数
        console.error('错误:', status, error);
    },
    complete: function(xhr, status) {  // 请求完成的回调函数 (无论成功或失败)
        console.log('完成:', status);
    }
});
    success: function (res) {
      switch (parseInt(res.code)) {
        case 200:
          dtd.resolve(res);
          break;
        case 230:
          dtd.reject(res);
          break;
        case 401:
        case 402:
        case 211:
        // '登录过期,请重新登录';
          setTimeout(() => {
            router.push('/login')
          }, 1500)

          break;
        case 406:
          // 权限变化
          setTimeout(() => {
            router.push('/login')
          }, 1500)
          break;
        case 201:
          dtd.reject(res);
          break;
        default:
          dtd.reject(res);
          break;
      }
    },
    error: function (err) {
      let statusText = err.statusText;
      if (statusText == "abort") return;
      let messageStr = '';
      switch (statusText) {
        case 'timeout':
          messageStr = "请求接口超时,请稍后再试"
          break;
        case 'error':
          messageStr = '请求接口异常,请尝试操作刷新页面!'
          break;
        case 'parsererror':
          messageStr = '返回解析错误'
          break;
        case 'abort':
          messageStr = ""
          break;
        case 'Internal Server Error':
          messageStr = "服务器内部错误";
          break;
      }
      if (err.status == 503 || err.status == 504) {
        messageStr = "服务暂不可用,请稍后重试"
      }
      if (options.data instanceof FormData && statusText == 'error') {
        messageStr = "上传文件已改变或者删除,请重新选择文件"
      }
      if (isOnLine() == 'offLine') {
        messageStr = "当前网络不通,请检查网络"
      }
      if (messageStr && showError) {
        message({
          message: messageStr,
          type: 'error',
          duration: 1666
        })
      }
      dtd.reject({
        message: messageStr || "",
        code: 1000
      });
    }

配置项

url

  • 说明: 请求的 URL 地址。可以是绝对 URL 或相对 URL。
  • 类型: String
  • 默认值:
  • 示例:
    url: 'https://api.example.com/data'
    

type

  • 说明: HTTP 请求的方法类型。决定了请求的性质,比如获取数据或提交数据。
  • 类型: String
  • 可选值: 'GET', 'POST', 'PUT', 'DELETE', 'HEAD', 'OPTIONS', 'PATCH'
  • 默认值: 'GET'
  • 示例:
    type: 'POST'
    

data

  • 说明: 发送到服务器的数据。可以是对象、数组或字符串。data 属性会被转换为查询字符串(对于 GET 请求)或请求体(对于 POST 请求)。
  • 类型: ObjectString
  • 默认值: null
  • 示例:
    data: {
        key1: 'value1',
        key2: 'value2'
    }
    // 或者字符串
    data: 'key1=value1&key2=value2'
    

dataType

  • 说明: 预期从服务器返回的数据类型。jQuery 将根据该配置自动解析服务器的响应数据。
  • 类型: String
  • 可选值: 'json', 'xml', 'html', 'text', 'script', 'jsonp'
  • 默认值: 'text'
  • 示例:
    dataType: 'json'
    

success

  • 说明: 请求成功时的回调函数。该函数在请求成功(HTTP 状态码在 200 到 299 之间)时执行。
  • 类型: Function
  • 参数: data, textStatus, jqXHR
    • data: 从服务器返回的数据。
    • textStatus: 描述请求状态的字符串。
    • jqXHR: jQuery 的 jqXHR 对象(类似于原生的 XMLHttpRequest 对象)。
  • 默认值: null
  • 示例:
    success: function(data, textStatus, jqXHR) {
        console.log('成功:', data);
    }
    

error

  • 说明: 请求失败时的回调函数。该函数在请求失败时执行(如网络错误、HTTP 状态码大于等于 400)。
  • 类型: Function
  • 参数: jqXHR, textStatus, errorThrown
    • jqXHR: jQuery 的 jqXHR 对象(类似于原生的 XMLHttpRequest 对象)。
    • textStatus: 描述请求状态的字符串(如 'timeout', 'error', 'abort', 'parsererror')。
    • errorThrown: 描述错误的字符串。
  • 默认值: null
  • 示例:
    error: function(jqXHR, textStatus, errorThrown) {
        console.error('错误:', textStatus, errorThrown);
    }
    

complete

  • 说明: 请求完成后的回调函数。该函数在请求完成(无论成功或失败)时执行。
  • 类型: Function
  • 参数: jqXHR, textStatus
    • jqXHR: jQuery 的 jqXHR 对象。
    • textStatus: 描述请求状态的字符串。
  • 默认值: null
  • 示例:
    complete: function(jqXHR, textStatus) {
        console.log('完成:', textStatus);
    }
    

headers

  • 说明: 设置请求的自定义 HTTP 头部。
  • 类型: Object
  • 默认值: null
  • 示例:
    headers: {
        'Authorization': 'Bearer your-token',
        'Custom-Header': 'value'
    }
    

timeout

  • 说明: 设置请求的超时时间。单位是毫秒。如果请求在指定时间内未完成,则会触发 error 回调。
  • 类型: Number
  • 默认值: 0(表示没有超时限制)
  • 示例:
    timeout: 5000 // 5 秒
    

cache

  • 说明: 是否缓存 GET 请求的结果。默认为 true,即缓存。如果设置为 false,则在请求 URL 后自动添加时间戳,防止缓存。
  • 类型: Boolean
  • 默认值: true
  • 示例:
    cache: false // 不缓存 GET 请求
    

contentType

  • 说明: 请求头中 Content-Type 的值。指定发送到服务器的数据类型,通常用于 POST 请求。默认为 application/x-www-form-urlencoded; charset=UTF-8
  • 类型: String
  • 默认值: 'application/x-www-form-urlencoded; charset=UTF-8'
  • 示例:
    contentType: 'application/json; charset=UTF-8' // 发送 JSON 数据
    

processData

  • 说明: 是否处理发送到服务器的数据。默认为 true,即将 data 参数转换为查询字符串。设置为 false 时,data 参数不会被转换,适用于发送原始数据(如 FormData 对象)。
  • 类型: Boolean
  • 默认值: true
  • 示例:
    processData: false // 发送 FormData 对象
    

async

  • 说明: 是否异步请求。默认为 true。如果设置为 false,请求将是同步的(通常不推荐使用)。
  • 类型: Boolean
  • 默认值: true
  • 示例:
    async: false // 同步请求
    

crossDomain

  • 说明: 是否允许跨域请求。如果 url 和当前页面的域不一致,则会自动设置为 true
  • 类型: Boolean
  • 默认值: false
  • 示例:
    crossDomain: true // 允许跨域请求
    

jsonp

  • 说明: 仅在 dataType 设置为 'jsonp' 时使用。指定 JSONP 请求的回调函数名称。
  • 类型: String
  • 默认值: null
  • 示例:
    jsonp: 'callback' // JSONP 回调函数名称
    

beforeSend

  • 说明: 请求发送之前的回调函数。可以在这里设置请求头部等。
  • 类型: Function
  • 参数: jqXHR
    • jqXHR: jQuery 的 jqXHR 对象(类似于原生的 XMLHttpRequest 对象)。
  • 默认值: null
  • 示例:
    beforeSend: function(jqXHR) {
        jqXHR.setRequestHeader('X-Custom-Header', 'value');
    }
    

示例代码

contentTypeprocessData 的 POST 请求

$.ajax({
    url: 'https://api.example.com/submit',
    type: 'POST',
    dataType: 'json',
    contentType: 'application/json; charset=UTF-8',
    processData: false,
    data: JSON.stringify({
        name: 'John Doe',
        age: 30
    }),
    success: function(response) {
        console.log('请求成功:', response);
    },
    error: function(xhr, status, error) {
        console.error('请求失败:', status, error);
    }
});

cachetimeout 的 GET 请求

$.ajax({
    url: 'https://api.example.com/data',
    type: 'GET',
    dataType: 'json',
    cache: false, // 不缓存
    timeout: 10000, // 10 秒
    success: function(response) {
        console.log('请求成功:', response);
    },
    error: function(xhr, status, error) {
        console.error('请求失败:', status, error);
    }
});

参考文档


  • 7
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值