【问题标题】:ajax GET failing when JSON content over 1MB on GoDaddy host当 GoDaddy 主机上的 JSON 内容超过 1MB 时,ajax GET 失败
【发布时间】:2019-03-17 03:18:28
【问题描述】:

我在 jquery 中有一个非常简单的 ajax GET 请求,它在我的本地测试服务器上运行良好。如果我将网页与 php 服务一起移动到托管服务器 (GoDaddy),它会失败并显示 textStatus = "error"errorThrown = ""。 Chrome 显示

net::ERR_EMPTY_RESPONSE。

这一切都在 1 秒内发生,因此不是超时问题。

如果我截断记录数以使返回的 json 小于 1MB,则它可以正常工作。

如果我将服务器代码从 GoDaddy 网页调用到我的本地服务器以获取所有记录 (1.8MB),一切都很好。任一站点的良好回报将在不到一秒的时间内完成。

当 json 回显中有超过 1MB 的数据时,什么可能导致 GoDaddy 基本上不返回任何数据?

php 服务器例程:

if (isset($_REQUEST['_SESSION'])) die("Get lost Dweeb!");
error_reporting(E_ALL | E_STRICT);
header('Access-Control-Allow-Origin: *');
$date_code = $_GET['date_code'];
$region = $_GET['region'];
$chargers = array();
$chg_count = 0;
$ftime = filemtime("chargers.json");

if ($ftime != $date_code) {
    $aTeslaChargers = json_decode(file_get_contents("chargers.json"),true);
    foreach($aTeslaChargers as $aTeslaCharger) {
        if ($aTeslaCharger['region'] == $region) {
            $chargers[] = $aTeslaCharger;
            $chg_count++;
            //if ($chg_count > 1972) break;
        }
    }
}
$json = json_encode(array(array("date_code" => $ftime), $chargers));
echo $json;

javascript 例程:

var url = 'https://www.website.com/get_data.php?date_code=0&region=north_america'; 

    var jqxhr = $.ajax({
                url: url,
                type: "GET",
                crossDomain: true
    })
    .done(function(response) {
        console.log(new Date());
        //var data = $.parseJSON(response);
        //console.log(data);
        console.log(response.length);
    })
    .fail(function(jqXHR, textStatus, errorThrown) {
        console.log(new Date());
        console.log(errorThrown);
    });

【问题讨论】:

  • 仅供参考,您无需设置 crossDomain 选项。事实上,我从未见过一个好的用例。它实际上仅用于在本地域请求上强制执行 JSONP 请求

标签: php json ajax get


【解决方案1】:

好吧,我偶然发现了一个解决方案。它是在 echo 之前添加一个 header 语句,这似乎允许 echo 大于 1MB。

header("Content-Type: application/json");
echo json_encode(array(array("date_code" => $ftime), $chargers));

我现在需要更多地了解这一点,并在各种浏览器中进行检查。同样有趣的是,数据现在作为对象返回,因此无需对其进行 json 解码。

我怀疑 GoDaddy 服务中有一些东西默认了长度,但我不确定。我的服务器再次没有这样的行为。

【讨论】:

  • “同样有趣的是数据现在作为一个对象返回”
  • 你应该接受这个答案。我怀疑会有更多人遇到这个问题,这是一个很好的规范解决方案
  • 自上周三以来我面临同样的问题,您的回答确实保存了我的网站,谢谢!你知道这个问题的更好解决方案是什么吗?
猜你喜欢
  • 2012-12-02
  • 1970-01-01
  • 1970-01-01
  • 2013-01-04
  • 1970-01-01
  • 2011-04-10
  • 1970-01-01
  • 2019-05-15
相关资源
最近更新 更多