Ajax请求头设置Content-type

编程知识 更新时间:2023-04-05 06:36:31

一:原生ajax请求头
使用setRequestHeader函数:
先调用open方法打开一个url:

xhr.open("post", "/save");

设置数据格式:
1.发送json格式数据:

xhr.setRequestHeader("Content-type","application/json; charset=utf-8");

2.发送表单数据:

xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8");

3.发送纯文本(默认值):

xhr.setRequestHeader("Content-type", "text/plain; charset=utf-8");

4.发送html文本:

xhr.setRequestHeader("Content-type", "text/html; charset=utf-8");

5.编码可带可不带:

// 不带字符编码写法
xhr.setRequestHeader("Content-type", "application/json");

6.值对大小写不敏感:

xhr.setRequestHeader("Content-type","Application/JSON; charset=utf-8");

二:Jquery中ajax设置请求头
全局的:
// 这个是全局的,所有的ajax请求都会加上这个请求头

 $(document).ajaxSend(function (event, xhr) {
            xhr.setRequestHeader("custom-header", "custom-info") ;  // 增加一个自定义请求头
    });

局部的:
- 第一种

 $('xxx').ajax({
  //...
  beforeSend:function(jqXHR,options){
    jqXHR.setRequestHeader("custom-header", "custom-info") ;  // 增加一个自定义请求头
  }
  //...
}) ;
  • 第二种
  $('xxx').ajax({
  //...
  headers:{
   "Referer": "http://www.365mini" // 有些浏览器不允许修改该请求头       
   ,"User-Agent": "newLine" // 有些浏览器不允许修改该请求头        
   ,"X-Power": "newLine"       
   ,"Accept-Language": "en-US"
  }
  //...
}) ;

作者:else05
链接:https://www.jianshu/p/ce9686344781
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。

更多推荐

Ajax请求头设置Content-type

本文发布于:2023-04-05 06:36:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/fce5fa61acce12ac4d90027269f44654.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Ajax   Content   type

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!

  • 45311文章数
  • 14阅读数
  • 0评论数