技术频道


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>

<script>
$.ajax({
	type: "get",
	async: true,
	url: "https://example.com/ajax/xxx", 
	dataType: "json",   
	beforeSend : function () {
		...
	},
	success : function(data) {
		...
	},
	error : function(err_msg) {
		...
	}
});
</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);
  });

Fetch API GET 方式:

async function getData() {
  const url = "https://example.org/products.json";
  try {
    const response = await fetch(url);
    if (!response.ok) {
      throw new Error(`Response status: ${response.status}`);
    }

    const json = await response.json();
    console.log(json);
  } catch (error) {
    console.error(error.message);
  }
}

Fetch API POST 方式:

const response = await fetch("https://example.org/post", {
  method: "POST",
  body: JSON.stringify({ username: "example" }),
  // ...
});


const response = await fetch("https://example.org/post", {
  method: "POST",
  headers: {
    "Content-Type": "application/x-www-form-urlencoded",
  },
  // Automatically converted to "username=example&password=password"
  body: new URLSearchParams({ username: "example", password: "password" }),
  // ...
});

jQuery Ajax、 JavaScript Fetch 扩展阅读:


 

CommandNotFound ⚡️ 坑否 - 其他频道扩展阅读:



发表评论