提示信息

jquery , ajax,get或post时,带上headers

韦敏予 已关注

在jQuery的ajax()方法中,可以使用headers选项来设置HTTP请求头。以下是一些示例:

使用GET请求:

  1. $.ajax({
  2. url: 'https://example.com/api/data',
  3. type: 'GET',
  4. headers: {
  5. 'Authorization': 'Bearer YOUR_TOKEN_HERE',
  6. // 更多自定义headers
  7. },
  8. success: function(result) {
  9. console.log(result);
  10. },
  11. error: function(error) {
  12. console.error(error);
  13. }
  14. });

使用POST请求:

  1. $.ajax({
  2. url: 'https://example.com/api/data',
  3. type: 'POST',
  4. headers: {
  5. 'Content-Type': 'application/json',
  6. 'Authorization': 'Bearer YOUR_TOKEN_HERE',
  7. // 更多自定义headers
  8. },
  9. data: JSON.stringify({
  10. key1: 'value1',
  11. key2: 'value2'
  12. }),
  13. success: function(result) {
  14. console.log(result);
  15. },
  16. error: function(error) {
  17. console.error(error);
  18. }
  19. });

在上述代码中,我们创建了一个包含'Authorization'和(对于POST请求)'Content-Type'头部的请求。你可以根据需要添加更多的请求头。

    遇到难题? "AI大模型GPT4.0、GPT" 是你的私人解答专家! 点击按钮去提问......
韦敏予 关注 已关注

最近一次登录:2024-03-15 16:23:54   

暂时还没有签名,请关注我或评论我的文章
×
免费图表工具,画流程图、架构图