我的jQuery代码在我的聊天应用程序中不起作用

时间:2014-12-25 21:18:21

标签: jquery json codeigniter

我的jQuery代码有问题吗?我在教程中观看,但在我的教程中它不起作用。当我点击提交时,没有任何反应。

你知道问题是什么吗?

我的view

<script type="text/javascript">

    var chat_id = "<?php echo $chat_id; ?>" ;
    var user_id = "<?php echo $user_id; ?>" ;
    var base_url = "<?php echo base_url(); ?>" ;



    $(document).ready(function() {
    $('#submit_message').on('click', function() {
        var chat_message_content = $('#chat_message').val();
        if(chat_message_content == "") { return false; }
        $.post(base_url + "chat/ajax_add_chat_message", { chat_message_content : chat_message_content, chat_id : chat_id, user_id : user_id } , function(data){

            alert(data);

        }, "json");


        return false;
    });
    });
</script>

我的controller(称为聊天):

public function ajax_add_chat_message() {

    $chat_id = $this->input->post('chat_id');
    $user_id = $this->input->post('user_id');
    $chat_message_content = $this->input->post('chat_message_content');
    $this->load->model('db_chat');
    $this->db_chat->add_chat_message($chat_id , $user_id , $chat_message_content);
}

1 个答案:

答案 0 :(得分:1)

您需要在ajax_add_chat_message()函数中返回一些内容才能获得警报:

public function ajax_add_chat_message() {

    $chat_id = $this->input->post('chat_id');
    $user_id = $this->input->post('user_id');
    $chat_message_content = $this->input->post('chat_message_content');
    $this->load->model('db_chat');
    $saved = $this->db_chat->add_chat_message($chat_id , $user_id , $chat_message_content);
    // $saved return TRUE or FALSE

    $response = array('err' => true, 'msg' => 'failed');
    if($saved)
       $response = array('err' => false, 'msg' => 'success');

    return $this->output->set_content_type('application/json')
                        ->set_output(json_encode($response));

}

在您的视图文件中:

$.post(base_url + "chat/ajax_add_chat_message", { chat_message_content : chat_message_content, chat_id : chat_id, user_id : user_id } , function(data){

    alert(data.msg);
    console.log(data);

}, "json");