每当我按下表单中的“提交请求”按钮时,不会弹出任何错误,也不会将我重定向到PHP脚本中记录的页面。关于为什么会发生这种情况的任何想法?
来自网页的代码w / form:
<form id="consultation-reservation" action="actions/consultation-request.php" method="post">
<input name="fullname" type="text" placeholder="Full Name (Required)" class="mt5" />
<input name="phonenumber" type="text" placeholder="Phone Number (Required)" class="mt5" />
<input name="emailaddress" type="text" placeholder="E-Mail Address (Required)" class="mt5" />
<textarea name="comments" placeholder="Additional Comments/Questions" class="mt10"></textarea>
<p class="hidden" id="consultation-reservation-error">Please verify all required fields are complete.</p>
<a class="button" id="consultation-reservation-submit">Submit Request</a>
</form>
<script type="text/javascript">
$(document).ready(function(){
$("#consultation-reservation-submit").click(function(){
$("#consultation-reservation").submit();
});
});
$('#consultation-reservation').submit(function(e) {
register();
e.preventDefault();
});
function register()
{
jQuery.ajax({
method: "POST",
url: "actions/consultation-request.php",
data: $('#consultation-reservation').serialize(),
dataType: "json",
success: function(msg){
if(parseInt(msg.status)==1)
{
window.location=msg.txt;
}
else if(parseInt(msg.status)==0)
{
error(1,msg.txt);
}
}
});
}
function hideshow(el,act)
{
if(act) $('#'+el).hide(0).slideDown(500, 'linear');
else $('#'+el).hide();
}
function error(act,txt)
{
if(txt) $('#consultation-reservation-error').html(txt);
$('#consultation-reservation-error').hide(0).slideDown(500, 'linear');
}
</script>
应该通过ajax执行的PHP脚本:(我将把mysql_real_escape_string应用于包含表单数据的变量,但还没有)
<?php
if(empty($_POST['fullname']) || empty($_POST['phonenumber']) || empty($_POST['emailaddress']))
{
die('{status:0,"txt":"Please verify all required fields are complete."}');
}
$name = $_POST['fullname'];
$phonenumber = $_POST['phonenumber'];
$email = $_POST['emailaddress'];
$comments = $_POST['comments'];
if(!(preg_match("/^[\.A-z0-9_\-\+]+[@][A-z0-9_\-]+([.][A-z0-9_\-]+)+[A-z]{1,4}$/", $_POST['emailaddress'])))
die('{status:0,"txt":"Please Provide a Valid E-Mail Address."}');
echo '{status:1,txt:"consultation-request-successful"}';
?>
答案 0 :(得分:2)
echo '{status:1,txt:"consultation-request-successful"}';
以上是无效的JSON,因为它没有使用txt
和status
键周围的双引号。您将响应数据类型指定为json
,因此jQuery将尝试将响应解析为JSON,如果失败,它将运行错误处理程序(如果已设置)而不是成功处理程序。
所以要么添加双引号,要么以另一种方式构建JSON:
$response = array('status' => 1, 'txt' => 'consultation-request-successful');
echo json_encode($response);
以这种方式构建JSON要好得多,因为所有引号都会被自动处理,值中的特殊字符也会根据需要进行转义。