繁体   English   中英

PHP(Codeigniter)和ajax帮助

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM