【问题标题】:codeigniter not returning json/ajax responsecodeigniter 不返回 json/ajax 响应
【发布时间】:2019-02-05 12:28:05
【问题描述】:

我已经阅读了很多关于 codeIgniter ajax 响应的内容。我已经多次修改了我的 ajax 脚本,但 codeIgniter 没有返回 json 响应,尽管我在 web 控制台的网络选项卡下使用 firefox 开发者浏览器进行调试时看到了响应。这是我写的

AJAX 脚本

$("#class_id").change(function(){

    var class_id = $("#class_id").val();
    alert(class_id);
    alert("<?php echo base_url(); ?>teacher/index.php?teacher/set_class_id");
        $.ajax({
            method: "POST",
            url: "<?php echo base_url(); ?>teacher/index.php?teacher/set_class_id",
            dataType: 'json',
            data: {class_id: class_id},

            success: function(response) {
                $("#res").html(reponse.class_id);
            }
    });
    return false;

});

控制器

function set_class_id()
{
    if ($this->session->userdata('teacher_login') != 1)
        redirect(base_url(), 'refresh');

        //echo "dsdsd".$this->input->POST('class_id');
        if (!empty($this->input->POST('class_id')))
        {
            $page_data = array('class_id' => $this->input->POST('class_id'));
            //$response["JSON"] = json_encode($page_data);
            $response = array('class_id' => $this->input->POST('class_id'));

            echo json_encode($page_data);

            $this->load->view('backend/index', $page_data);

        }
}

【问题讨论】:

  • 你为什么要使用$this-&gt;load-&gt;view('backend/index', $page_data); ???回声后
  • 在这里获得价值? //echo "dsdsd".$this-&gt;input-&gt;POST('class_id');?
  • 没有您的回复,我们该如何帮助您
  • 这很混乱,你是在向另一个页面发送数据吗?我的意思是当你在 ajax 上抛出数据之后,加载的视图会是什么?
  • @devpro 是的,我在使用 firebug 的浏览器中看到了响应,并且响应状态为 200。

标签: php ajax codeigniter


【解决方案1】:

您是否尝试过使用

$this->output
    ->set_content_type('application/json')
    ->set_output(json_encode(array('foo' => 'bar')));

另外,查看输出类以获取更多信息Codeigniter Output Class

【讨论】:

  • 是的,我收到了这个回复SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data at line 1 column 2 of the JSON data
【解决方案2】:

所以我想出了一个办法。仅使用 php,我使用提交按钮将 class_id 发送到控制器,然后检查页面上的响应以启用主题下拉菜单。虽然我还没有弄清楚为什么 ajax 还没有工作。谢谢大家的意见

【讨论】:

    猜你喜欢
    • 2013-09-12
    • 2016-07-30
    • 1970-01-01
    • 2011-05-12
    • 2015-03-29
    • 2011-10-27
    • 1970-01-01
    • 2014-10-24
    • 2013-09-20
    相关资源
    最近更新 更多