我想用CodeIgniter和Ajax爲我的網站做一個非常簡單的php聊天。這些消息保存在一個html文件中,而不是保存在數據庫表中。無論何時點擊發送按鈕,頁面都會刷新,即使它沒有被刪除,我也不知道什麼是錯誤的。 這裏是我的代碼: 我的控制器代碼:如何在codeigniter中使用ajax?
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>
wha'ts錯誤?有檢查瀏覽器的控制檯? – YVS1102
沒有錯誤,但是當我單擊發送按鈕時,由於Ajax,頁面刷新並且不應該顯示。我的Ajax代碼一定有問題,但我不知道它是什麼。 – eri
var postData = $(#message).serializeArray(); #消息引用 – Rijin