【问题标题】:Codeigniter - Call another controller from a view using ajaxCodeigniter - 使用 ajax 从视图中调用另一个控制器
【发布时间】:2013-02-19 07:15:33
【问题描述】:

最初我试图从一个控制器加载两个视图。

在提交时,我使用 ajax 动态地将一个视图传递给一个控制器,并将另一个视图传递给另一个控制器。这是控制器的骨架

function edit(){     
    if (!$this->login_model->is_logged_in())
    {
        redirect('auth/login', 'refresh');
    }   
    $this->load->library('form_validation');    
    $this->data['custom_error'] = '';

        //------------- Getting Student data----------------

    if ($this->form_validation->run('students') == false)
    {
         $this->data['custom_error'] = (validation_errors() ? '<div class="form_error">'.validation_errors().'</div>' : false);

    } else
    {                            
        $data = array(
                'username' => $this->input->post('username'),
                'city' => $this->input->post('city')
        );

        if ($this->student_model->edit('students',$data,'id',$this->input->post('id')) == TRUE)
        {
            redirect(base_url().'index.php/students/manage/');
        }
        else
        {
            $this->data['custom_error'] = '<div class="form_error"><p>An Error Occured</p></div>';

        }
    }

    $this->data['result'] = $this->codegen_model->get('students','id,username,city,created_on,date_created','id = '.$this->uri->segment(3),NULL,NULL,true);

    $this->data['message'] = $this->db->get('messages')->result();

            //---------------------- Posting student data for Edit--------------
    $this->load->view('pheader');
    $this->load->view('/students/students_edit', $this->data);  

            //-------- loading comment controller for comment box --------------
            $msg_data['result'] = $this->db->get('messages')->result();
            $this->load->view('commentView', $msg_data);
}

所以问题是当我提交messages_view 时,两个控制器都已加载,但我只需要加载一个控制器

这是我的 student_edit 视图,我在其中编辑我的详细信息

<?php     

echo form_open(current_url()); ?>
<?php echo $custom_error; ?>
<?php echo form_hidden('id',$result->id) ?>

        <p><label for="username">Username<span class="required">*</span></label>                                
        <input id="username" type="text" name="username" value="<?php echo $result->username ?>"  />
        <?php echo form_error('username','<div>','</div>'); ?>
        </p>

        <p><label for="city">City<span class="required">*</span></label>                                
        <input id="city" type="text" name="city" value="<?php echo $result->city ?>"  />
        <?php echo form_error('city','<div>','</div>'); ?>
        </p>
        <?php echo form_submit( 'submit', 'Submit'); ?>
</p>

<?php echo form_close(); ?>

这是我从控制器单独加载的commentView

<div id="content-table-inner">
    <table border="0" width="100%" cellpadding="0" cellspacing="0">
        <?php foreach ($result as $comment): ?>

            <tr valign="top">
                <p>Posted By : <?=$comment->created_by?></p> 
                <p>Posted On : <?=$comment->created->on?></p> 
                <p>Message : <?=$comment->message?></p> 
            </tr>
            <br/>
        <?php endforeach; ?>
        </table>
        <div class="submitComment" id="insertbeforMe">
            <h3>Add a message</h3>
            <form id="form" method="POST" action="">
             <p>
                 <textarea name="message"></textarea>
            </p>
                <input type="hidden" value="<?=base_url()?>" id="baseurl"/>
                <button name="submit comment">Submit Comment</button>
            </form>
        </div>
        <script type="text/javascript">
        function comment(){
            var baseurl = $('#baseurl').val();
            $('.submitComment').click(function(){
                $.ajax({
                    url : baseurl + 'index.php/comment/insert',
                    data : $('form').serialize(),
                    type: "POST",
                    success : function(comment){
                        $(comment).hide().insertBefore('#insertbeforMe').slideDown('slow');
                    }
                })
                return false;
            })
        }
        </script>

</div>

谁能告诉我是什么问题?

【问题讨论】:

  • 为什么不改ajax来调用控制器呢?
  • @ajreal :我将提交两个表单,那么如何在一个网页中向两个不同的控制器提交两个不同的表单?
  • 两个请求可以合并为一个

标签: php codeigniter jquery


【解决方案1】:

如果我理解正确的话……

您应该捕获的事件是表单的“提交”,而不是提交按钮的“点击”。您实际上是在运行 AJAX 请求提交表单。

试试这样的方法:

$('form').on('submit', function(e) {
    e.preventDefault(); // this prevents the form from submitting

    // do AJAX stuff
});

【讨论】:

    【解决方案2】:

    除非我弄错了,否则您将事件附加到 '.submitComment' div 上的点击事件。

    您不应该给按钮一个 id 并将 .click 事件附加到它吗? 然后您需要定义要通过 ajax 调用的视图以返回一些您的函数可以使用的 json:

    Javascript:

           $('#button').click(function(){
                        $.ajax({
                            url : baseurl + 'index.php/comment/insert',
                            data : $('form').serialize(),
                            type: "POST",
                            dataType: "json",
                            success : function(comment){
                                $('table').append('<tr><p>'+comment.createdby+'</p><p>'+comment.createdon+'</p><p>'+comment.message+'</p></tr>');
                            }
                        })
                        return false;
           })
    

    控制器方法(注释/插入):

    function insert() {
        $comment = $this->input->post('message');
        $result = $this->commentModel->insert($comment);
        if($result["OK"]) {
            $data['json'] = json_encode(array('createdon' => $result["createdon"], 'createdby' => $result["createdby"], 'message' => $result["message"]));
            $this->load->view('json_comment_view', $data);
        }
        //ELSE deal with errors (flashdata etc...)
    } 
    

    视图(通过 ajax 加载):

    <?php
        $this->output->set_header('Content-Type: application/json; charset=utf-8');
        echo $json;
    ?>
    

    我还没有测试过这段代码 - 或者在大约一年的时间里广泛使用过 codeigniter,但所涵盖的概念应该能让你走上你想要实现的目标的正确轨道。告诉我!

    【讨论】:

    • 仍然没有得到它,因为以前的表单仍然抛出 flash 错误
    • 你能澄清一下吗?以前的什么形式?另外-您到底收到了什么错误?谢谢。
    • 就像我有两个视图 edit_person_details_view 和 cmets_view 都来自不同的控制器但显示在同一个网页上。我需要分别提交两者。我该怎么做?
    • 您需要一个控制器来正常加载视图。然后从该视图中,您应该使用 javascript 调用另一个控制器,该控制器又加载自己的视图。第二个视图使用 jQuery 加载或 ajax 调用加载到与第一个相同的页面中。你能为其他视图提供额外的源代码吗?您的问题中只显示一种形式。
    • 在您的附加代码中,在您的评论下方:// loading comment controller for comment box 您实际上并没有加载另一个控制器,而是加载了一个附加视图。在您最初的问题中,您还说提交 messages_view 时出现问题是commentView?您还说您有两个表单,并且需要将它们的提交与另一个分开。我想您的意思是当您提交第二个表单时,第一个表单会显示验证错误?如果页面上有多个表单,您应该在 ajax 中为表单使用类或 id 选择器。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-12
    • 1970-01-01
    • 1970-01-01
    • 2016-01-01
    • 1970-01-01
    相关资源
    最近更新 更多