PHP (Codeigniter) 和 ajax 帮助

标签 php javascript ajax jquery

我正在尝试创建一个类似 Twitter 的应用程序,用户在表单中输入一些数据,并通过使用 ajax(jquery 库),用户可以实时看到他们的提交位于所有其他数据的顶部。

它的工作方式是用户提交表单并将数据提交到数据库,我还想使用ajax将数据添加到数据列表中。

我的问题是,如果我在 php 方法中 echo $var; ,我只能访问 PHP 方法从 ajax 请求创建的数据,这对我来说看起来不正确,有人可以告诉我吗请问我做错了什么?

    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请求类型。

检查这个article ,使用 is_ajax 来了解何时 echo 以及何时加载 View 是一种干净的方法!

因此在 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 已正式发布,插件现已替换为助手,因此我更新了我的答案。

关于PHP (Codeigniter) 和 ajax 帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4828748/

相关文章:

php - json_encode 在处理多字节子字符串时返回 false

PHP - 将 SQL GROUP BY 作为数组返回?

javascript - jQuery ) 语法错误 : missing : after property id)

javascript - 是否有在呈现元素时触发的函数?

php - Ajax表单多次提交。有时

jquery - 我正在向服务器发出 Ajax 发布请求,所有数据都很好,但我的名字和姓氏正在更新为 "undefined"

php - mysql中是自动增量循环吗?

php - 如何在 Yii 1.x 中获取当前 URL?

javascript - 如何使用backbone和backbone.validation提交表单

javascript - 在下拉列表中的类别中拆分选项