![](/img/trans.png)
[英]POST method not supported when submitting multiple forms through the same JS code. (405)
[英]Multiple the same forms and POST method?
我在一页上有多个相同形式的实例(名称/电子邮件/消息字段)。 它们都共享一个类(“ .contact-form”),并且具有不同的类(动态生成的ID)。
我使用jQuery Tools Validator验证了它们(尽管无关紧要,因为我对此没有任何问题):
$(".contact-form").validator();
问题出在我想像的sendmail.php文件中,这就是我获取所有POST值并验证它们的方式:
//grab the fields
$address = trim($_POST['address']);
$title = trim($_POST['title']);
$message = $_POST['message'];
//check if empty
if(empty($name) || empty($title) || empty($message)) {
$wrong = true;
}
if($wrong) {
http_response_code(400);
} else {
// do stuff
http_response_code(200);
}
现在,我面临的问题是:
注意 :未定义的索引:第3行上的mysitesaddress中的地址
有什么想法如何解决它/检查每个表格而不是仅检查第一个表格/发送后清除POST数据吗? 我敢肯定,在PHP中有一种简单的方法可以做到这一点,因为我对这种语言(大多是前端人员)并不熟悉,所以对您的帮助将不胜感激。
谢谢!
(我已经在谷歌上搜索了一段时间了,但是看起来“ POST”是一个棘手的名字,我主要使用的是Wordpress /博客/论坛相关内容...)
[更新]
这是每种形式的HTML代码:
<div class="wrapper">
<form class="contact-form" action="sendmail.php" method="post" novalidate="novalidate">
<input name="title" type="text" required="required" />
<input name="address" type="email" required="required" />
<textarea name="message" required="required" ></textarea>
<input type="Submit" value="Submit" />
</form>
<div class="sucess">
Success message that replaces form ^.
</div>
</div>
该通知表示“地址”键不存在。
您应该检查$_POST
变量中的索引是否已设置/存在,例如使用PHP isset()函数。
造成这种情况的原因是,您不是以每种形式发送地址,而只是以第一种形式发送地址。
有关如何使用isset进行检查的示例代码:
if ( isset($_POST['address']) ) {
//only set $address to the $_POST value if it is set
$address = trim($_POST['address']);
}
我看不到您的HTML表单代码,但我猜您的表单标签看起来像这样
<form action="sendmail.php" method="post">
这将从提交的表单中获取所有字段,并通过$ _POST将其发送到sendmail.php。 处理完数据后(edwardmp为确保在尝试分配变量之前确保数据已存在提供了很好的提示),然后将页面重定向到某种成功登录类型或返回原始表单页面。 我一直使用的方法是:
if($wrong) {
$error = "Please check your entry and try again.";
header("Location: http://example.com/formpage.html?error=" . htmlencode($error),true,303);
exit();
} else {
// do stuff
$msg = "Your form was successfully submitted.";
header("Location: http://example.com/formpage.html?msg=" . htmlencode($msg),true,303);
exit();
}
这种设计使其可以通过重新加载页面来清除$ _POST数据,并允许您将消息发送回原始页面,该页面将通过$ _GET ['msg']或$ _GET ['error']显示。 这应该阻止表单错误提交。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.