如何在codeigniter中使用ajax?

时间:2016-10-17 09:19:13

标签: php jquery ajax codeigniter

我正在尝试使用CodeIgniter和Ajax为我的网站进行非常简单的php聊天。消息保存在html文件中,而不是数据库表中。每当我点击发送按钮时,页面都会刷新,即使它没有被使用,我也不知道该怎么回事。 这是我的代码:     我的控制器代码:

class Chat_con extends CI_Controller{

function construct(){
    parent::_construct();

}

public function index(){
    $this->load->model('login_model');

$d['info']=$this->login_model->display_user_data();//this info is sent to view to display the username of the person who is using the chat
$d['message']=$this->read_conv();
$this->load->view('chat_view',$d);
}
function write_conv() {
    $this->load->helper('directory');
        $this->load->helper('url');
        $this->load->helper('file');
        $this->path = "application" . DIRECTORY_SEPARATOR . "files"
             . DIRECTORY_SEPARATOR;
        $this->file = $this->path . "log.html";
        $m=$this->input->post('usermsg');
        $u=$this->session->userdata('username');
        write_file($this->file,"<div class='msgln'>(".date("g:i A").")     <b>".$u."</b>: ".stripslashes(htmlspecialchars($m))."<br></div>",'a');
        $this->index();

    }

    function read_conv(){
        $this->load->helper('directory');
        $this->load->helper('url');
        $this->load->helper('file');
        $this->path = "application" . DIRECTORY_SEPARATOR . "files"
             . DIRECTORY_SEPARATOR;
        $this->file = $this->path . "log.html";
        $string = read_file($this->file);
        return $string;
    }

}

我的部分观点:

 <div id="chatbox">//this is the div where the messages are displayed
<?php  echo $message;  ?></div>

//this is the form
<form name="message" id="message"action="<?php echo base_url();?   
 >chat_con/write_conv" method='post'>
    <input name="usermsg" type="text" id="usermsg" size="63" /> <input
        name="submitmsg" type="submit" id="submitmsg" value="Send" />
 </form>

//脚本

<script type="text/javascript">
    $(document).ready(function() {
    $("#message").submit(function(e) { 
        e.preventDefault();
        var postData = $(#message).serializeArray();
        var formActionURL = $(this).attr("action");
        $.ajax({

            url: formActionURL,
            type: "POST",
            data: postData,
         }).done(function(data) {
            alert("success");
         }).fail(function() {
            alert("error");
         }).always(function() {
            $("#submitmsg").val('submit');
        });
    });
}
</script>

3 个答案:

答案 0 :(得分:1)

  1. var postData = $(#message).serializeArray();应该是:
    var postData = $("#message").serializeArray();
  2. 如果问题仍然没有得到解决,请尝试在alert()之前添加console.log()e.preventDefault()进行调试,然后调试您的js代码。
    例如alert('dummy text for debug');

答案 1 :(得分:0)

实际上,你确实有一些错误。你只是不看他们。当您执行任何与JQuery / Javascript相关的操作时,您需要能够查看正在发生的事情。

查看如何debug using your browser

就个人而言,我喜欢你使用firefox和一个名为firebug的插件。

所以我已经采取了你的代码并简化了它(我不会评论其余的php),发现错误,修复它们并且我有一点玩它来帮助展示一些东西。还有很多东西需要学习......

但是你最终不会撕掉你的头发,这就是我想出来调试它的原因。

控制器

class Chat_con extends CI_Controller {

    public function __construct() { // This didn't have any __ at all
        parent::__construct(); // error here only one _ not two __
        $this->load->helper('url');
    }

    public function index() {
        $d['info']    = 'Dummy Info';
        $d['message'] = 'What are you going to say?';
        $this->load->view('chat_con_view', $d); //
    }

    /**
     * Process the AJAX Call and send back an HTML Response
     *
     */
    public function write_conv() {
        echo "I said " .$this->input->post('usermsg');
    }
}

视图

<div id="chatbox">
    <?php echo $message; ?>
</div>

<form name="message" id="message" action="<?php echo base_url(); ?>chat_con/write_conv" method="post">
    <input name="usermsg" type="text" id="usermsg" size="63"/>
    <input name="submitmsg" type="submit" id="submitmsg" value="Send"/>
</form>

<script src="<?= base_url(); ?>assets/js/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function () {
        $("#message").submit(function (e) {
            console.log("The Submit button was pressed - that is a good sign.");
            e.preventDefault();
            var postData = $('#message').serializeArray();
            var formActionURL = $(this).attr("action");
            console.log("postData = " + JSON.stringify(postData));
            console.log("formActionURL = " + formActionURL);
            $.ajax({
                url: formActionURL,
                type: "POST",
                data: postData,
            }).done(function (data) {
                $('#chatbox').html(data);
                alert("success");
            }).fail(function () {
                alert("error");
            }).always(function () {
                $("#submitmsg").val('submit');
            });
        });
    });
</script>

PS。请将此与您所拥有的内容进行比较,以便您可以看到自己犯了哪些错误并问自己,“为什么他们不会从我的屏幕上跳出来?” (我喜欢过于戏剧化。)

我可以说更多,但希望这会告诉你如何至少调试这样的东西,并记得去了解如何使用浏览器开发人员控制台。它会在各方面都有所帮助。

干杯。

答案 2 :(得分:0)

这对我有用,请查看

  $(document).ready(function() {
    $("#message").submit(function(e) { 
       e.preventDefault();
    var postData = $(this).serialize();
    var formActionURL = $(this).attr("action");
    $.ajax({
        url: formActionURL,
        type: "POST",
        data: postData,
     }).done(function(data) {
        console.log(data);
     }).fail(function() {
        alert("error");
     }).always(function() {
        $("#submitmsg").val('submit');
    });
});
});

HTML:

   <form name="message" id="message"action="demo.php" method='post'> // edit ur form action properly here
<input name="usermsg" type="text" id="usermsg" size="63" /> 
<input name="submitmsg" type="submit" id="submitmsg" value="Send" />