【问题标题】:CodIgniter: why I get html response instead of json response when sending ajax requestCodeIgniter:为什么我在发送 ajax 请求时得到 html 响应而不是 json 响应
【发布时间】:2012-11-21 14:51:19
【问题描述】:

我向服务器发送和 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);”之后的任何代码不起作用,例如。警报(“嗨”); !

【问题讨论】:

  • html页面包含什么?
  • @ekims : html 页面是 WAMPSERVER 主页!!
  • 你不需要使用parseJSON(result):如果你使用type: "json"获取,result应该已经被解析了。
  • @itachi 我已经调试了 我疯狂的 HTML 响应而不是 JSON ......这个简单的建议帮助我解决了所有问题。谢谢。

标签: php ajax json codeigniter


【解决方案1】:

我不知道这是否能完全解决您的问题(可能涉及到一个显示挂钩或其他正在生成 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));
}

【讨论】:

  • 我试过这段代码,但响应仍然是一个 html 页面“WAMPSERVER Homepage”。并且模型没有错误,我通过url调用函数并简单地回显数据!
【解决方案2】:

您的模型中似乎有一些错误,您得到的 HTML 响应是 CI 错误消息。

只是为了调试,回显不带 json_encode 的 $data,然后通过 URL 直接调用该函数。

【讨论】:

    【解决方案3】:

    尝试关注

    $('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!'));
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-22
      • 2022-11-24
      • 1970-01-01
      • 2016-09-09
      • 1970-01-01
      • 2014-09-13
      • 1970-01-01
      • 2015-07-09
      相关资源
      最近更新 更多