2012-12-04 37 views
0

我发送和ajax请求到服务器,我想接收json响应,但是我收到html响应,这段代码中有什么错误?CodIgniter:为什么我发送ajax请求时得到html响应而不是json响应

//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);”之后的任何代码不起作用,例如。警报( “你好”); !

+0

什么html页面包含哪些内容? – ekims

+1

尝试使用绝对网址。 – itachi

+0

@ekims:html页面是WAMPSERVER主页! – sahar

回答

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)); 
} 
+0

我试过这段代码,但是响应仍然是一个html页面“WAMPSERVER Homepage”。 并且在模型中没有错误,我通过url调用函数并简单地回显数据! – sahar

0

您的模型似乎有错误,并且您收到的HTML响应是CI错误消息。

仅用于调试,在不使用json_encode的情况下回显$ data,然后直接通过URL调用该函数。

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!')); 
} 
+0

它也一样! – sahar

相关问题