【问题标题】:Why is my Ajax request sending "Content-Type: application/x-www-form-urlencoded" when I have dataType: "JSON"?当我有 dataType:“JSON”时,为什么我的 Ajax 请求会发送“Content-Type:application/x-www-form-urlencoded”?
【发布时间】:2014-07-14 11:51:54
【问题描述】:

当我使用以下响应按钮单击时,它会调用(通过使用 console.log() 进行验证),但是,它生成的 http 请求具有标题“Content-Type: application/x- www-form-urlencoded; charset=UTF-8\r\n"。不应该是json吗?

我在 Ubuntu 上使用谷歌浏览器 34.0.1847.132。 jQuery 版本 1.8.3。

提前致谢!

function action (mode) {
    console.log("action called with mode " + mode);
    $.ajax({
      type: "POST",
      url: '/saas.php',
      data: {
          action: (mode == 1)? "start" : "stop"
      },
      dataType: "json",
      success: function(data) {
          //alert(data);
          if (data.msg != null) {
              alert(data.msg);
          } else {
            if (mode == 1) {
                document.getElementById('createLoadGen').innerHTML = 'creating loadGen...';
                setTimeout(checkStatus, 1000);
            }
          }
      }
    });
    if (mode == 2) {
        document.getElementById('createLoadGen').innerHTML = '<button onclick="action(1)" >create LoadGen</button>';
        document.getElementById('deleteLoadGen').style.display = 'none'
    }
}

【问题讨论】:

  • 你混淆了两件事。 application/x-form 只是 MIME 类型。这就像发送数据的使用标准。 Json 是一种以 mime 类型发送和包装的数据格式。另外,我建议您查看 jquery 手册。 dataType 没有定义数据的发送方式。它只是告诉 jquery 你期望一个 JSON-String 作为答案。
  • @newBee — 错误。 application/x-www-form-urlencodedapplication/json 是用于描述不同类型内容的不同 MIME 类型。发送包裹在 URL 编码数据中的 JSON 是很不明智的。
  • 但是他没有发送 json 格式的数据。因此,mime 类型很好。
  • 像往常一样,阅读documentation 实际上会有所帮助:"dataType:您希望从服务器返回的数据类型。如果没有指定时,jQuery 将尝试根据响应的 MIME 类型推断它 [...]"

标签: javascript jquery html


【解决方案1】:

一般不会。 request 中的 Content-Type 标头描述 request 正文中的内容,而不是 response 中预期的内容类型(描述预期的响应格式是 Accept 标头的工作)。

默认情况下,jQuery 将使用 HTML 表单使用的标准编码对数据进行编码。

现在,可能是服务器希望将请求格式化为 JSON,在这种情况下,您需要对 jQuery 调用进行以下修改:

  1. 假设您正在发送 JSON
  2. 将您发送的内容编码为 JSON,而不是让 jQuery 自行编码

这样的:

  data: JSON.stringify({
      action: (mode == 1)? "start" : "stop"
  }),
  contentType: "application/json",

sass.php 将不得不 parse the JSON request 而不是让 PHP 在后台不可见地执行此操作,而只是从 $_POST 中提取数据。

【讨论】:

  • 感谢@Quentin 和其他人评论和回答这个问题!真的很有帮助。
  • 感谢您的解释。一直在寻找设置 AJAX 语法属性的示例,而您的示例恰好显示了将格式语法传递给 JSON.stringify() 然后传递给 AJAX 的确切含义。我在网上找到的其他示例会将JSON.stringify() 的内容用单引号和双引号括起来,并且将System.String 转换为Generic.IDictionary. 时总是会出错
猜你喜欢
  • 1970-01-01
  • 2019-06-14
  • 1970-01-01
  • 1970-01-01
  • 2017-09-26
  • 2021-01-19
  • 1970-01-01
  • 2018-12-17
  • 2018-10-10
相关资源
最近更新 更多