技术频道


jQuery AJAX 及 fetch 请求完整示例

传统 jQuery Ajax 方式:


<script>
  // 使用jQuery发起POST请求
  $.ajax({
    url: 'https://example.com/api/endpoint', 
    method: 'POST', 
    contentType: 'text/json;charset=utf-8', // 请求头的Content-Type 如 application/x-www-form-urlencoded
    data: {
      key1: 'value1',
      key2: 'value2'
    }, // 要发送的表单数据
    success: function(data) {
      // 成功回调函数,处理返回的数据
      console.log('Response:', data);
    },
    error: function(xhr, status, error) {
      // 失败回调函数,处理请求失败的情况
      console.error('Error:', status, error);
    }
  });
</script>

下面是一个简单的使用 fetch 的例子:


fetch 是一个在浏览器中提供的用于发起网络请求的 API,它是基于 Promise 的,并且提供了一种更简洁和强大的方式来进行 HTTP 请求,相比传统的 XMLHttpRequest。

fetch('https://api.example.com/data')
  .then(response => {
    // 处理响应
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json(); // 解析响应体为 JSON
  })
  .then(data => {
    // 处理解析后的数据
    console.log(data);
  })
  .catch(error => {
    // 处理错误
    console.error('There has been a problem with your fetch operation:', error);
  });

jQuery Ajax、 JavaScript Fetch 扩展阅读:



发表评论