CodeIgniter:为什么我在发送ajax请求时得到html响应而不是json响应

时间:2012-12-04 02:17:47

标签: php ajax json codeigniter

我发送和ajax请求到服务器,我想收到json响应,但我收到html响应,这段代码有什么问题?

//jquery code

$('select[name=category]').click(function(){
    $.ajax({
    url: "/index.php/category/get_categories",
    type: "post",  
    dataType: "json",
    cache: false,      
    success: function (result) { 
        var arr = jquery.parseJSON(result);
        alert(arr);
        }      
    });
});

//php code

public function get_categories(){
    $data = $this->category_model->get_cats_names_ids();
    echo json_encode($data);
}

响应是一个html页面而不是json对象,并且不显示警告框。 当我删除dataType:“json”时,会出现警告框并包含html页面! 以及“var arr = jquery.parseJSON(result);”之后的任何代码不起作用,例如警报( “你好”); !

3 个答案:

答案 0 :(得分:3)

我不知道这是否能完全解决你的问题(可能有一个显示挂钩或其他视图机器正在生成html),但从这里开始。

规则1:永远不要回应控制器中的任何内容。调用视图或使用output::set_output

规则2:始终正确设置内容类型。

public function get_categories(){
    $data = $this->category_model->get_cats_names_ids();
    $this->output->set_header('Content-type:application/json');
    $this->output->set_output(json_encode($data));
}

答案 1 :(得分:0)

您的模型中似乎存在错误,您获得的HTML响应是CI错误消息。

只是为了调试,在没有json_encode的情况下回显$ data,然后通过URL直接调用该函数。

答案 2 :(得分:0)

尝试以下

$('select[name=category]').click(function()
{
 $.post( '<?php echo site_url('category/get_categories'); ?>', { 'var': 1 },
       function(response) {
       if(response.success)
    {
         var arr = response.message;
                     alert(arr);
    }       
      },"json");


});

 public function get_categories()
 {
    $data = $this->category_model->get_cats_names_ids();
    echo json_encode(array('success'=>true,'message'=>$data));
    //for testing replace above line with
    // echo json_encode(array('success'=>true,'message'=>'Hello!'));
 }
相关问题