当按下后退按钮时,让 jQuery 触发 Ajax 请求
我有一个包含 80 多个动态生成的输入框的页面,当用户将表单提交到另一个 .php 页面并且其中一个输入包含非数字值时,它将使用以下命令将它们发送回输入页面: ,同时它将错误注册到会话变量中。我使用 javascript:history.back() 的原因是因为它存储表单中的值,即使您按下后退按钮也是如此。但因为它正在缓存页面,所以我无法在同一个 .php 脚本中输出错误,因此我添加了一个元素和一些 Ajax 代码。 Ajax 代码检索另一个名为 error.php 的文件,其中包含:
<?php
header("Cache-Control: no-cache");
session_start();
if(isset($_SESSION['error']))
{
echo $_SESSION['error'];
unset($_SESSION['error']);
}
?>
这是在页面自行加载时检索的,但在使用 history.back()
时则不会检索,看起来如下所示不开火:
<script type="text/JavaScript">
$(document).ready(function(){
$("#error p").load("error.php");
});
</script>
有什么想法吗?
谢谢,
贾斯汀
I have a page with 80+ dynamically generated input boxes, when the user submits the form to another .php page and one of the inputs contains a value that is not numeric, it will send them back to the inputs page using: <?php header("Location: javascript:history.back()"); ?>
, at the same time it registers the error in a session variable. The reason why I'm using javascript:history.back(), is because it stores the values that were in the form, even when you press the back button. But because it is caching the page I can't output the error in the same .php script, so I added a an element and some Ajax code. The Ajax code retrieves another file called error.php, this contains:
<?php
header("Cache-Control: no-cache");
session_start();
if(isset($_SESSION['error']))
{
echo $_SESSION['error'];
unset($_SESSION['error']);
}
?>
This is retrieved when the page is loaded on it own, but not when history.back()
is used, it looks like the following isn't firing:
<script type="text/JavaScript">
$(document).ready(function(){
$("#error p").load("error.php");
});
</script>
Any ideas?
Thanks,
Justin
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
header("Location: javascript:history.back()")
通常是不明智的。使用绝对路径,即
header('Location: /forms/input.php');
Using
header("Location: javascript:history.back()")
is generally ill-advised.Use an absolute path i.e.
header('Location: /forms/input.php');
您可以完全避免提交表单并通过 AJAX 调用发送数据 - 服务器可以验证数据并发回“成功”或验证错误列表。
如果成功,则转到下一个 URL(可能在成功消息旁边指定)。
如果失败,则修改当前页面以指示问题所在。这可以避免您必须重新创建整个表单(因为您永远不会离开页面),而且还可以进行可靠的服务器端验证
You could avoid submitting the form entirely and send the data via an AJAX call - the server could validate the data and send back either "success" or a list of validation errors.
If success, move on to the next URL (possibly specified alongside the success message)
If failed, modify the current page to indicate what the problems were. This avoids you having to re-create the whole form (as you never leave the page) but also allows for reliable server-side validation