表单提交后,如何使用php在页面中向下跳转

时间:2019-03-14 16:28:45

标签: javascript php html

我有一个名为buyback.php的页面。在该页面中有一个表单,在表单的动作中,我说action="buyback.php",因为我需要页面在表单提交后自行调用。表单在页面底部。在这种形式下,有一个具有id结果的div。重新加载页面后,如何使页面跳至该div?

我知道提交表单后可以使用ajax发送电子邮件,提交表单后不会刷新页面,但我不知道ajax。我说通过使用php发送电子邮件:-

if (mail($to, $subject, $message, $header)) {
    $result = "Thank you for contacting us. We will reply you as soon as possible";
} else {
    $result = "Message Sending Failed, try again";
}

并且div是:-

<div id="result"><?php if(isset($result)){ echo $result; } ?></div>

我知道如果我说action="buyback.php#result",我可以向下滚动到该div,但是问题在于,如果页面向下滚动后手动刷新,则由于页面中的#result会再次向下滚动url,并非所有人都会发现他们需要删除#result

我想尝试在php中使用document.getElementById("result").scrollIntoView();来使页面跳转。我试着说:-

echo "<script>";
echo "document.getElementById(\"result\").scrollIntoView();";
echo "</script>";

在php块的末尾,但这没有用,它所做的就是将javacript行添加到页面顶部,并且没有向下滚动。我该怎么做才能使其正常工作?我还可以用其他方式向下滚动吗?

2 个答案:

答案 0 :(得分:0)

获取结果div并检查是否包含文本(如果该div包含文本填充的帖子已提交)

var result = document.getElementById("result").innerHTML

通过这一行,我们在结果div内获取HTML。

然后检查结果是否有长度。 (如果长度为0,则没有消息)

if(result.length > 0){
    document.getElementById("result").scrollIntoView()
}

答案 1 :(得分:0)

为什么不使用AJAX?

除了成功或错误消息外,您无需从PHP返回其他任何内容,它还使您的页面更具动态性。这是提交工作表以使用PHP发送邮件的示例。

index.html

<form name="sendMail" method="POST" onsubmit="return sendMail()">
   <label for="yourName">Name: </label><input name="yourName">
   <label for="yourEmail">E-Mail: </label><input name="yourEmail">
</form>

javascriptApp.js

function sendMail(){
   let data = {
      name: document.sendMail.yourName.value;
      email: document.sendMail.yourEmail.value;
   };
   const Http = new XMLHttpRequest();
   const url='path/to/your/phpfile.php';
   Http.open("POST", url);
   Http.send(data);
   Http.onreadystatechange=(e)=>{
      //Form send with AJAX, now scroll down.
      if( e.responseText == "error" ){
         alert("There was an error sending your data. Try again.");
      }else{
         document.getElementById("result").scrollIntoView();
      }
   }
return false;
}

mail.php

您只需使用PHP生成邮件内容并正常发送即可。

if (mail($to, $subject, $message, $header)) {
    echo "done";
} else {
    echo "error";
}

此外,我建议您使用jQuery,它使AJAX请求的代码更少,请查看:

https://jquery.com/

相关问题