尝试通过控制器加载带有 # 标签的部分页面

Trying to load a portion of page with # tag through conroller

我有一个页面,它实际上有两个部分,可以通过 # 标签访问,例如 login#signinlogin#signup。当页面第一次加载时,它显示登录表单 #signin 没有问题。

因此登录不会导致问题,因为它在 folder/login 加载。但是当我尝试将 folder/login#signup 直接加载到注册部分时,它给出了一个没有视图 login#signup.php 的错误。如何应对这种情况?

$this->load->view('workers/login#signup'); 不工作。

当我不输入 #signup 时,它会加载奇怪的登录表单。

我将详细说明我对错误原因的初步评论,以及如何解决问题。

问题的原因

如评论中所述,您不能使用锚点查看。例如,这 not 工作:

view('workers/login#signup'); // The #signup should not be here.

documentation 状态:

Loading a View

To load a particular view file you will use the following method:

$this->load->view('name');

Where name is the name of your view file.

文件名是"name",不是"name#signup"。

再往下,

The .php file extension does not need to be specified unless you use something other than .php.

这意味着,当您使用 view('name') 时,CodeIgniter 将默认加载文件 name.php。如果您在其中包含 #signup,那么 CodeIgniter 将无法找到 name#signup.php,因为该文件不存在。

正确的处理方式

您提到您正在使用表单验证,因此我们需要确保在转换过程中不会丢失任何值。

这里有一个关于如何处理它的简单解释:

function login() {

    // Data to be passed to the view (you may or may not already have this)
    // More info: https://codeigniter.com/user_guide/general/views.html#adding-dynamic-data-to-the-view
    $data = array();


    // Validation has failed...
    $this->form_validation->run() == FALSE ) {

        // Set variable to redirect to #signup upon page load
        $data['redirect_to_signup'] = true;
    }


    // Load view with $data which contains values to be passed to the view
    $this->load->view('workers/login', $data);

}

在您的 workers/login 视图文件中,我们只需要检查 redirect_to_signup 值是否存在。如果它确实存在,那么我们可以使用 some simple JavaScript to scroll down#signup 形式:

<?php if (isset($redirect_to_signup) && $redirect_to_signup === true): ?>
<script>
    var top = document.getElementById('signup').offsetTop;
    window.scrollTo(0, top);
</script>
<?php endif; ?>

因为您的验证对象仍然有效,您可以使用内置的 CodeIgniter 函数通过 set_value() 辅助函数预加载您的表单元素。例如:

<input type="text" name="email" value="<?php echo set_value('email'); ?>">

这有望解释如何实现您的目标:

  1. 验证用户提交的表单;和
  2. 如果有错误,请重新加载带有验证消息的表单;和
  3. 向下滚动到页面上的 #signup 表单。

一种替代方法是使用 redirect('login#signup'),但我不推荐这种方法。您需要将表单值和验证错误保存到会话中,以便在下一页显示它们。您还 运行 遇到用户可能单击刷新按钮然后所有值都将丢失的问题。