在 jQuery 中,可以使用 $.ajax
方法发起 POST 请求并携带自定义请求头。以下是一个基本的示例:
$.ajax({
url: 'your-endpoint-url', // 你的请求URL
type: 'POST', // 请求类型
headers: {
'Custom-Header': 'Your-Custom-Value' // 自定义请求头
},
data: {
key1: 'value1', // 发送的数据
key2: 'value2'
},
success: function(response) {
// 请求成功后的回调函数
console.log(response);
},
error: function(xhr, status, error) {
// 请求失败后的回调函数
console.error(error);
}
});
在这个示例中,url
是你想要发送 POST 请求的服务器端点,type
指定了请求类型为 POST。headers
对象用来添加自定义的 HTTP 请求头,data
对象包含了你想要发送的数据。success
和 error
函数分别定义了请求成功和失败时的回调函数。
请确保将 'your-endpoint-url'
替换为你的服务器端点,'Your-Custom-Value'
替换为你的自定义请求头的值,以及 key1
和 key2
替换为你想要发送的数据的键值对。
此外,如果你的数据是 JSON 格式的,你还需要设置 contentType
和 dataType
:
$.ajax({
// ... 其他配置
contentType: 'application/json', // 发送的数据类型
dataType: 'json', // 期望的响应数据类型
data: JSON.stringify({
key1: 'value1',
key2: 'value2'
}),
// ... 其他配置
});
使用 JSON.stringify
将 JavaScript 对象转换为 JSON 字符串,以便作为请求体发送。