zoukankan      html  css  js  c++  java
  • HTTP Headers Content-Type 详解

    Content-Type 实体头部用于指示资源的 MIME 类型 media type 。

    语法

    Content-Type: text/html; charset=utf-8
    Content-Type: multipart/form-data; boundary=something
    
    参数 说明
    media-type 资源或数据的 MIME type
    charset 字符编码标准
    boundary boundary

    常见 media-type

    • text/plain
    • application/json
    • application/x-www-form-urlencoded
    • multipart/form-data

    几种请求设置 Content-Type 的方式

    XMLHttpRequest

    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open('POST', 'https://xxx.xxx.com/xxx', true);
    xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xmlhttp.send('a=1&b=2');
    
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.open('POST', 'https://xxx.xxx.com/xxx', true);
    xmlhttp.setRequestHeader('Content-Type', 'application/json');
    xmlhttp.send(JSON.stringify({ a: 1, b: 1 }));
    

    JQuery.ajax

    $.ajax({
      type: 'post',
      url: 'https://xxx.xxx.com/xxx',
      contentType: 'application/x-www-form-urlencoded',
      data: { a: 1, b: 1 }, // ajax 会自动转成 a=1&b=2
      success: function () { },
    })
    
    $.ajax({
      type: 'post',
      url: 'https://xxx.xxx.com/xxx',
      contentType: 'application/json',
      data: JSON.stringify({ a: 1, b: 1 }),
      success: function () { },
    })
    

    JQuery.ajax 本质是封装 XMLHttpRequest , contentType 即 content-type , 默认 application/x-www-form-urlencoded 。

    注意

    • data 如果不是 string , 会使用 jQuery.param 转换成 = & 拼接的 search 格式,然后用 xml.send 方法发送。
    • dataType 预期服务器返回的数据类型。会通过下面对象转换后插入 accept。
    accepts: {
    	"*": allTypes,
    	text: "text/plain",
    	html: "text/html",
    	xml: "application/xml, text/xml",
    	json: "application/json, text/javascript"
    },
    

    Fetch

    fetch('https://xxx.xxx.com/xxx', {
      method: 'post',
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
      },
      body: 'a=1&b=2',
    })
    
    fetch('https://xxx.xxx.com/xxx', {
      method: 'post',
      headers: {
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({ a: 1, b: 1 }),
    })
    

    三种数据传输方式

    Query String Parameters

    从问号 (?) 开始的 URL(查询部分)。

    Form Data

    application/x-www-form-urlencoded

    Request Payload

    application/json

  • 相关阅读:
    SpringBoot入门篇--读取资源文件配置
    SpringBoot入门篇--使用Thymeleaf模板引擎进行页面的渲染
    SpringBoot入门篇--热部署
    NOI2017 游记
    BZOJ 2754 【SCOI2012】 喵星球上的点名
    codeforces 741D Arpa’s letter-marked tree and Mehrdad’s Dokhtar-kosh paths
    BZOJ 4407 于神之怒加强版
    BZOJ 2956 模积和
    BZOJ 4584 【APIO2016】 赛艇
    BZOJ 4591 【SHOI2015】 超能粒子炮·改
  • 原文地址:https://www.cnblogs.com/whosmeya/p/14315632.html
Copyright © 2011-2022 走看看