当我有dataType:"JSON"时,为什么我的Ajax请求发送"Content-Type:application/x-www-form-urlencoded"?

pac*_*tie 1 html javascript jquery

当我使用以下内容响应按钮单击时,它调用它(通过使用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'
    }
}
Run Code Online (Sandbox Code Playgroud)

Que*_*tin 8

不一般.请求中的Content-Type标头描述了请求正文中的内容,而不是响应中预期的内容类型(描述预期的响应格式是Accept标题的作业).

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

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

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

这样:

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

sass.php然后必须解析JSON请求,而不是让PHP在后台无形地执行它,只是从中取出数据$_POST.