资源被解释为Document但在Chrome Developer Tools中使用MIME类型application/json警告进行传输

tam*_*are 42 jquery jquery-forms-plugin google-chrome-devtools

我有以下代码片段,它使用jQuery Form插件将表单发布到服务器(在ajax中).

  var options = {
    dataType: "json",
    success: function(data) { 
      alert("success");
    } 
  }; 

  $form.ajaxSubmit(options);
Run Code Online (Sandbox Code Playgroud)

表格:

<form enctype="multipart/form-data" id="name_change_form" method="post" action="/my_account/"> 
<div style='display:none'><input type='hidden' name='csrfmiddlewaretoken' value='6c9b552aaba88b8442077e2957e69303' /></div> 
  <table> 
    <tr> 
      <td> 
        <label for="id_first_name">First name</label>:
      </td> 
      <td> 
        <input name="first_name" value="Patrick" maxlength="30" type="text" id="id_first_name" size="30" /> 
      </td> 
    </tr> 
    <tr> 
      <td> 
        <label for="id_last_name">Last name</label>:
      </td> 
      <td> 
        <input name="last_name" value="Sung" maxlength="30" type="text" id="id_last_name" size="30" /> 
      </td> 
    </tr> 
  </table> 
  <input type="hidden" name="form_id" value="name_change_form" /> 
</form> 
Run Code Online (Sandbox Code Playgroud)

ajax实现工作正常.但是我收到了警告

资源解释为Document但使用MIME类型application/json进行传输

在Chrome开发者工具中.我想找出为什么警告,甚至更好的解决方法.

我改为使用$.post而且神奇地从那时起错误就消失了.我不知道为什么$.post有效,但不是$form.ajaxSubmit.如果有人可以提供他们的解释,这将是伟大的.至少,这个问题已得到解决.以下是新代码.

var url = $form.attr("action");
$.post(
  url, 
  $form.serialize(), 
  function(data) {
    alert("success");
  },
  "json"
); 
Run Code Online (Sandbox Code Playgroud)

小智 21

我遇到了同样的错误.对我有用的解决方案是:

从服务器端,在返回JSON响应时,更改content-type:text/html

现在浏览器(Chrome,Firefox和IE8)不会出错.

  • 我不同意.内容类型标题应与实际内容匹配,否则您可能会冒不了解客户端行为的风险.如果要发送JSON响应,则将content-type设置为text/html是没有意义的.您的客户需要发送正确的Accepts标头,详见[另一个答案](/sf/answers/3097469651/) (3认同)

Kud*_*nle 12

由于请求HTTP标头,通常会标记此类警告.特别是Accept请求标头. HTTP标头的MDN文档说明

The Accept request HTTP header advertises which content types, expressed as MIME types, the client is able to understand. Using content negotiation, the server then selects one of the proposals, uses it and informs the client of its choice with the Content-Type response header. Browsers set adequate values for this header depending of the context where the request is done....

application/json可能不在浏览器发送的Accept标头中的MIME类型列表中,因此警告.

自定义HTTP标头只能通过XMLHttpRequest或任何实现它的js库包装器以编程方式发送.

  • 这是最正确和最丰富的答案.我想知道为什么在我的浏览器中直接导航到JSON API端点时发生这种情况. (3认同)

Joh*_*ohn 7

这实际上是 Chrome 中的一个怪癖,而不是 JavaScript 库。这是修复:

为了防止消息出现并允许 chrome 在控制台中将响应很好地呈现为 JSON,请将查询字符串附加到您的请求 URL。

例如

var xhr_object = new XMLHttpRequest();

var url = 'mysite.com/'; // Using this one, Chrome throws error

var url = 'mysite.com/?'; // Using this one, Chrome works

xhr_object.open('POST', url, false);
Run Code Online (Sandbox Code Playgroud)


tam*_*are 2

我采取了不同的方法。我改用 $.post 并且从那时起错误就消失了。