页面刷新后移动到网页的一部分

时间:2011-10-16 10:23:56

标签: php jquery forms validation anchor

我有一篇给定文章的评论列表,我在评论下面有一个表单,供用户添加他们自己的评论。

我正在使用php进行一些表单验证。

这是一个过程:

  1. 用户填写表单(或不填写)并点击提交按钮。页面刷新。
  2. PHP验证用户输入,如果没有错误或提交注释 生成错误列表。
  3. 如果存在错误,则显示错误。

    问题是我希望错误显示在表单之前的注释之下,但是当epage刷新时,页面的顶部会显示,我需要它直接找到错误和形式(很像页面锚点)

  4. 这可能吗?

    单击提交按钮后调用

    if(empty($errors)){
            $result = post_comment('event',$event_id, $sendername, $senderemail, $userurl, $comment);
            if ($result == 'Correct') {
                //header('Location: /'.$_SERVER['REQUEST_URI']);
                header('Location: '.$_SERVER['REQUEST_URI']);
            }
            else {
                $send_error = $result;
    

    这就在评论和表单附近,如果存在错误,我想要去页面

    // If there was an error sending the email, display the error message
    if (isset($send_error)) {
    echo "<a name=\"commentsform\"></a>";
    echo "There was an error: ".$send_error;
    }
    /**
    * If there are errors and the number of errors is greater than zero,
    * display a warning message to the user with a list of errors
    */
    if ( isset($errors) && count($errors) > 0 ) {
        echo ( "<h2 class='errorhead'>There has been an error:</h2><p><span class='bold'>You forgot to enter the following field(s)</span></p>" );
        echo ( "<ul id='validation'>\n" );
        foreach ( $errors as $error ) {
            echo ( "<li>".$error."</li>\n" );
        }
    echo ( "</ul>\n" );
    }
            }
        }
    

3 个答案:

答案 0 :(得分:1)

为表单提供一个ID,可以通过URL跳转到该页面:

<div id="submitComment">
  <!-- Comment form here -->
</div>

然后将用户重定向回具有相应哈希标记的相同URL:

header('Location: http://www.example.com#submitComment');

答案 1 :(得分:1)

找到您的表单标签,它看起来像这样

<form action='yourpage.php'>

在URL之后放置一个哈希标记以及提交后将使用的锚点

<form action='yourpage.php#commentsform'>

答案 2 :(得分:1)

使用页面锚点,您可以通过更改网址中的哈希值将用户跳转到页面的任何部分。

让表单将用户发送到锚点,如下所示:

<form action='yourpage.php#comments'>

在您希望用户结束的地方制作一个锚:

<a name="comments"></a> 
相关问题