代码之家  ›  专栏  ›  技术社区  ›  Andy

响应类型正在从JSON更改为HTML,没有任何代码更改

  •  0
  • Andy  · 技术社区  · 6 年前

    我在CakePHP 2.x中有一个遗留应用程序

    它在控制器中有一个方法,该方法以如下结构输出JSON:

    {"id":59,"name":"Association of Southeast Asian Nations (ASEAN)","n_grouptags":1}
    

    使用的控制器方法 $this->response->type('json'); 设置 content-type application/json; charset=UTF-8 . 一切都好。

    我注意到,如果返回的数据超过了一定的长度 内容类型 text/html; charset=UTF-8 代码没有任何更改 .

    少量数据(内容类型= application/json -预期的):

    enter image description here

    enter image description here

    text/html -意外的):

    enter image description here

    enter image description here

    https://jsonlint.com/

    这是为什么?这取决于浏览器如何处理响应的长度,还是这是一个CakePHP问题?

    负责输出的PHP如下- 但是在上面给出的两个不同的输出之间并没有改变 :

        $this->autoRender = false; // No View (template) is associated with this
    
        $out = []; // Reset
    
        // $tags is some data from a model
        foreach ($tags as $k => $v) {
            $n_grouptags = 123; // Actual number comes from a Model 
            $out[] = ['id' => $k, 'name' => $v, 'n_grouptags' => $n_grouptags];
        }
    
        $this->response->type('json'); // We *want* a JSON response
    
        echo json_encode($out, JSON_FORCE_OBJECT); // Encode $out (the output) as JSON
    

    应用程序中的缓存被禁用: Configure::write('Cache.disable', true);

    1 回复  |  直到 6 年前
        1
  •  0
  •   ndm    6 年前

    控制器操作不应该回显数据,即使它可能在某些情况下工作,甚至在大多数情况下。输出不源于呈现视图模板的数据的正确方法是配置并返回响应对象(或字符串,但它与3.x不向前兼容)或使用序列化视图。

    根本的问题不是内容的长度,而是通常在响应对象可以发送头之前输出数据,这将导致它们被忽略,这将在响应发射器发挥作用之前发送一个字节时发生。

    output_buffering zlib.output_compression php.ini ),这将导致在超过缓冲区存储能力(在大多数情况下通常是4096字节)或显式刷新缓冲区(这将在脚本执行结束时自动发生)之前,回显数据被保留。

    tl;dr,要快速修复,请配置并返回响应:

    $this->response->body(json_encode($out, JSON_FORCE_OBJECT));
    return $this->response;
    

    推荐文章