Codeigniter如何在控制器中使用jquery

时间:2014-02-11 14:40:05

标签: php jquery node.js socket.io codeigniter-2

我正在使用codeigniter和nodejs进行实时通知。现在我只想让用户通知页面(控制器)上发生的最新变化。

因此,我正在使用socketio和nodejs来填充通知系统。代码如下:

var socket = io.connect( 'http://localhost:5000' );

$( "#messageForm" ).submit( function() {
    var nameVal = $( "input[name=nameInput]" ).val();
    var msg = $( "input[name=messageInput]" ).val();
    socket.emit( 'message', { name: nameVal, message: msg } ); //LN1
    alert('posted'); //Sent from client side
    return false;
});

//Receive the notification as soon as posted(for now, will get the same values posted above)
    socket.on( 'message', function( data ) {
        alert('got response');
        var actualContent = $( "#messages" ).html();
        var newMsgContent = '<li> <strong>' + data.name + '</strong> : ' + data.message + '</li>';
        var content = newMsgContent + actualContent;
        $( "#messages" ).html( content );
    });

我还想将更改保存到表单中,因此我将表单值发布到控制器,然后将其保存到数据库中。之后,我想要运行此代码。

所以,我想如果我能以某种方式得到它,那会更好:

Class Myclass extends CI_Controller
{
 //....contructors etc.

public function save_form()
{
   $name = $this->input->post('nameInput');
   $msg = $this->input->post('messageInput');
   $this->load->model('my_model'); //For saving to database
   $saved = $this->my_model->save($name, $msg); //returns true is saved

   if($saved)
   {
      //Now notify user
      //Please now tell me how to call the socketio javascript from here
   }
   redirect('form_url'); //Redirect back to form, from where is was submitted
}

//....other functions
}
}

那么有人能告诉我如何从控制器中调用javascript吗?这是一个好主意吗?实际上我可以使用从ajax调用控制器的方式,然后使用$.ajax.done(function(){ socket.emit( 'message', { name: nameVal, message: msg } ); },但是它太迟了,无法一直调用ajax调用。

提前致谢

1 个答案:

答案 0 :(得分:0)

创建视图文件Socket.php

类Myclass扩展了CI_Controller {         function __construct()     {         父:: __构建体();         $这 - &GT;负载&GT;辅助( 'URL');         $这 - &GT;负载&GT;助手( 'HTML');     }

  public function save_form()
   {
     $name = $this->input->post('nameInput');
     $msg = $this->input->post('messageInput');
     $this->load->model('my_model'); //For saving to database
     $saved = $this->my_model->save($name, $msg); //returns true is saved

    if($saved)
    {
        $this->load->view('Socket.php');
    }
    redirect('form_url'); //Redirect back to form, from where is was submitted
   }

}