【问题标题】:not getting appilcation/json in content-type in header没有在标题中的内容类型中获取应用程序/json
【发布时间】:2013-08-16 06:10:09
【问题描述】:

我想以 JSON 格式发送数据并获得响应以实现快速响应。所以我正在使用 AJAX。 为什么我会得到

"Content-Type text/html; charset=UTF-8"

为什么没有得到

内容类型应用程序/json

控制器

 public function testingMethod() {
        $this->autoRender = false;
        $urlVal = $_POST['urlVal'];
        $dataBack = json_encode($urlVal);
        if ($this->RequestHandler->isAjax()) {
            return $dataBack;
        }
    }

jQuery

$.ajax({
      type: "POST",
      url: pathname+"Frontends/testingMethod",
      data: 'urlVal=' + urlVal, 
      dataType: 'json',
      success: function (result) {
        console.log(result);
        alert(result);
     }
    });

标题

Response Headers

Connection  Keep-Alive
Content-Length  2382
Content-Type    text/html; charset=UTF-8     //why here not getting application/json
Date    Wed, 14 Aug 2013 10:17:38 GMT
Keep-Alive  timeout=5, max=94
Server  Apache/2.2.22 (Win32) PHP/5.4.3
X-Powered-By    PHP/5.4.3

【问题讨论】:

  • 我对 JQuery 不熟悉,但您几乎可以肯定在执行 POST 时需要设置“Content-Type”标头值(设置为“application/json”)。否则它可能只是默认值。
  • 您实际上并没有发送Content-Type 标头,这就是原因。

标签: php json jquery cakephp


【解决方案1】:

快速清单:

  1. .json 扩展添加到routes.php

    Router::parseExtensions('json');
    
  2. 在控制器中加载RequestHandler 类:

    public $components = array(
        'RequestHandler',
    );
    
  3. 在模型的 View 目录中创建一个 json 文件夹,并将 JSON 视图放置在那里。

  4. .json 附加到 URL:

    url: pathname+"Frontends/testingMethod.json",
    

这记录在JSON and XML views。值得阅读完整的文档,因为我描述的步骤并不是唯一可行的方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-04-21
    • 2012-11-30
    • 1970-01-01
    • 2013-11-17
    • 1970-01-01
    • 1970-01-01
    • 2018-09-05
    • 1970-01-01
    相关资源
    最近更新 更多