我正在尝试创建一个类似于Twitter的应用程序,其中用户将一些数据输入到表单中,并且通过使用ajax(jquery库),用户可以实时看到他们的提交到所有其他数据的顶部。
它的工作方式是用户提交表单并将数据提交到数据库,我还想使用ajax将数据添加到数据列表中。
我的问题是我只能访问PHP方法从ajax请求创建的数据,如果我在我的php方法中echo $var;
,这对我来说看起来不正确可以告诉我我做错了请?
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;
});
答案 0 :(得分:2)
在处理ajax请求时使用echo
没有问题,实际上它是要走的路。您也可以使用echo json_encode($output);
,具体取决于您的ajax请求类型。
使用is_ajax
检查此article以了解何时echo
以及何时加载您的观点是一种干净的方式!
所以在is-ajax_helper.php
文件夹中创建一个文件application/helpers/
:
<?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正式推出,插件现在已被帮助器取代,我已更新了我的答案。
答案 1 :(得分:0)
如今,您可以使用the input class中提供的$this->input->is_ajax_request()
来获得与@ifaour手工制作助手相同的结果。