2013-04-24 62 views
0

我有CI分析器就像这样: $ this-> output-> enable_profiler(TRUE) 在我的控制器中。启用CI分析器给出json解析错误

这是给JSON.parse:意外的非空格字符错误。当我关闭它的探查器时就OK了。

我发现Ajax响应文本有剖析的信息也是如此。

有人可以启发我这个。 如何在CI上打开剖析器并避免jason解析错误。 thanx提前

回答

2

我不喜欢这样的我的核心控制器类(扩展是CI_Controller是父类我所有的应用程序控制器):

if(!$this->input->is_ajax_request()) { 
    $this->output->enable_profiler(TRUE); 
} 

你也可以把:

$this->output->enable_profiler(FALSE); 

在您的ajax控制器方法中,该方法不包含profiler数据/字符串。

+0

那么profiler将不可用于ajax请求? – 2013-04-24 19:36:35

+0

只要那行代码存在就行了......但是您不希望它在返回JSON的Ajax请求中。 – jcorry 2013-04-24 19:40:21

0

首先,是的,我知道这个问题为+4岁,但2013至17年的Ajax调用了更受欢迎的在我们的网站/网络系统没有在服务器端性能的一些反馈是不是我的选择,所以这里是我做了什么:

应用程序\核心\ MY_Controller.php:(负载探查如图书馆)

<?php 
defined('BASEPATH') OR exit('No direct script access allowed'); 

class MY_Controller extends CI_Controller { 

    public function __construct(){ 
     parent::__construct(); 
     if(ENVIRONMENT === 'development'){ 
      $this->load->library('profiler'); //(don't use: $this->output->enable_profiler(FALSE), use it as a library!) 
     } 
    } 
} 

何时何地您需要它得到的输出只作为:(请记住扩展MY_Controller而不是CI_Controller)

<?php 
defined('BASEPATH') OR exit('No direct script access allowed'); 

class Somecontroller extends MY_Controller { 

    function ajaxCall() 
    { 
     // Do some stuff 
     $ret = array(
      'something' => 'yada yada yada', 
      '_profiler' => $this->profiler->run() 
      ); 
     header("Content-type:application/json"); 
     return print(json_encode($ret)); 
    } 

} 

现在你的Javascript中追加探查输出,而不破坏你的JSON结构:

<script> 
    var ajaxReturn; // Your prefered ajax call (native JS or jQuery or wathever) 
    if (typeof ajaxReturn === 'string') { 
     ajaxReturn = JSON.parse(ajaxReturn); 
    } 
    //-- Do some stuff 
    //-- Append the profiler output 
    document.getElementByTagName('body')[0].append(ajaxReturn._profiler); //-- or jQuery: $('body').append(ajaxReturn._profiler); 
</script> 

最后说明:

当然,这种形式给出将polute与剖析广泛的HTML你的Ajax调用,所以切勿将此分析器保留在PRODUCTION中,甚至在开发时只使用它来分析您的应用程序,否则如果没有它,情况可能会更好。

希望它可以帮助别人,因为它对我有用。