[英]PHP (Codeigniter) and ajax help
我正在嘗試創建一個類似Twitter的應用程序,在該應用程序中,用戶將一些數據輸入到表單中,並且通過使用ajax(jQuery庫),用戶可以實時查看其提交的所有其他數據的頂部。
它的工作方式是用戶提交表單並將數據提交到數據庫,我還想使用ajax將數據添加到數據列表中。
我的問題是如果我echo $var;
我只能訪問PHP方法從ajax請求創建的數據echo $var;
在我的PHP方法中,這看起來不正確我可以告訴我,我做錯了嗎?
public function feed() {
$this->load->library('form_validation');
$this->load->helper('dates');
$data['feed'] = $this->f->get_feed_by_employer($this->session->userdata('employer_id'));
$this->form_validation->set_error_delimiters('<div class="error">', '</div>');
$this->form_validation->set_rules('content', 'content', 'required|trim|max_length[140]');
$this->form_validation->set_rules('retrain', 'retrain position', 'trim|max_length[1]');
if ($this->form_validation->run() == FALSE)
{
echo validation_errors('<div class="error">', '</div>');
$this->template->build('employer/feed', $data);
}
else
{
$insert = array(
'content' => $this->input->post('content'),
'retrain' => $this->input->post('retrain'),
'created_at' => time(),
'employers_id' => $this->session->userdata('employer_id')
);
if($this->f->insert($insert)) {
echo $insert['content'];
}
}
}
和jquery
$('#employer_feed').submit(function(){
$.ajax({
url: '/employer/feed',
data: $('#employer_feed').serialize(),
type: 'POST',
success:function(html) {
$('#feed').append('<div class="feed_item">'+html+'</div>');
}
});
return false;
});
在處理ajax請求時使用echo
沒有問題,實際上這就是方法。 你也可以使用echo json_encode($output);
取決於您的ajax請求類型。
查看這篇文章 ,使用is_ajax
知道何時echo
以及何時加載您的視圖是一種干凈的方式!
因此,在application/helpers/
文件夾中創建文件is-ajax_helper.php
:
<?php
function is_ajax(){
return (isset($_SERVER['HTTP_X_REQUESTED_WITH'])
&& strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest');
}
並在您的config/autoload.php
:
$autoload['helper'] = array('is-ajax');
並檢查它是否是ajax電話!
編輯:
由於Codeigniter 2.0正式發布,並且插件現在已被助手替代,因此我更新了我的答案。
如今,您可以使用輸入類中提供的$this->input->is_ajax_request()
來獲得與@ifaour手工制作的助手相同的結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.