【问题标题】:XMLHttpRequest returns 406 error from PHP coded ServerXMLHttpRequest 从 PHP 编码的服务器返回 406 错误
【发布时间】:2020-04-09 08:25:07
【问题描述】:

所以我制作了这个应用程序并在我的 PHP 5.6 XAMPP 服务器上完美运行。很久以前,我将所有内容都转移到了 Host Gator 网站,我不记得它在哪个 PHP 版本上运行,但它按预期运行。但是,最近发生了错误,我已经对其进行了跟踪,罪魁祸首是 XMLHttpRequest 响应 406 错误。所以我可以更容易地追踪错误,我删除了额外的代码,只留下了会重现错误的行。 Host Gator 目前只能在 5.4 版本的 PHP 上运行。

这是我的 PHP 代码...这基本上返回一个 JSON 响应。

<?php
require 'sql.php';
require 'securitycheck.php';
$response = array();

try {

    //temporarily removed the codes that get the data sent by the client... Even with these removed, shouldn't cause errors...
    $response["code"] = 1;
    $response["message"] = "File Accepted";

    echo json_encode($response);

    //}
} catch (OAuthException $e) {
    echo $e->getMessage();
}
?>

现在这是我的客户端代码,它接受来自服务器的响应...

  var ajax = new XMLHttpRequest();
  ajax = new XMLHttpRequest();
  ajax.open("POST",'ajax/savefile.php', false);
  ajax.setRequestHeader("Accept", "application/json");
  ajax.setRequestHeader('Content-Type', 'application/upload');
  ajax.setRequestHeader("Http-X-Requested-With", "XMLHttpRequest");
  ajax.setRequestHeader("Security-Key", securitykey);
  ajax.send("filename=" + savedname + "&filedata=" + JSON.stringify(canvas.toJSON()) + "&width=" + canvas.getWidth() + "&height=" + canvas.getHeight() + "&command=update");  

  if (ajax.status == 200){
    response = JSON.parse(ajax.responseText);
    if (response.code == 1){
      alertify.notify(response.message, 'success', 3);
    }else{
      alertify.notify(response.message, 'error', 3);
      closeEvent.cancel = true;
    }
  }

它在我的服务器上运行良好,但在 HostGator 的服务器上抛出错误。有人可以帮我解决这个错误吗?当 HostGator 在我的 XAMPP 上运行时,如何不接受作为服务器的响应?非常感谢。

【问题讨论】:

  • 什么是application/upload?你为什么使用那种内容类型?这不是普通服务器将被配置为识别的标准内容类型。
  • @sideshowbarker 哦,我只是没有删除它,因为它没有导致任何错误。我应该把它改成什么?还是直接删除?
  • "Host Gator 目前仅在 5.4 版本的 PHP 上运行。" — PHP 5.4 已死。它最后得到了安全修复4 years, 7 months ago。如果无法为您提供适合这十年的 PHP 版本,请更换您的托管公司。
  • @Quentin 在 5.4 之后确实有 7.1,但它仍然给我同样的错误。

标签: javascript php json ajax xmlhttprequest


【解决方案1】:

406 error 表示:

服务器无法生成与请求的主动内容协商标头中定义的可接受值列表匹配的响应

您说ajax.setRequestHeader("Accept", "application/json");,所以您只接受 JSON 响应。

您提供的代码中没有任何内容可以测试 Accept 标头并在没有匹配项时输出 406。

支票的来源是一个谜,需要更多信息。检查主机的文档和日志文件可能是一个好的开始。

如果我要推测的话,我会建议某些东西正在检查您的 PHP 脚本的输出。既然你没有说header("Content-Type: application/json"); PHP 将默认声明它正在输出text/html

HTML 不是 JSON,因此很明显客户端不能接受输出。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-07
    • 2020-09-19
    • 2013-01-10
    • 1970-01-01
    • 1970-01-01
    • 2018-08-05
    • 2013-07-05
    相关资源
    最近更新 更多