gpt4 book ai didi

javascript - php post 返回 true 或无错误后 AJAX 重定向

转载 作者:行者123 更新时间:2023-12-03 08:48:29 25 4
gpt4 key购买 nike


我对 javascript 知之甚少,但不知何故我设法将表单数据发布到 php 文件。
现在我面临一个小问题,php 文件有一些验证,我想要的是如果有任何验证失败并且 php 文件返回 $error = 'Invalid data';我希望这个ajax请求只显示错误消息。

或者,如果它没有返回错误,或 $error = '';这个ajax请求重定向到thankyou.php页面。

HTML 文件:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

<script>
$(document).ready(function (e){
$("#frmContact").on('submit',(function(e){
e.preventDefault();
$.ajax({
url: "data.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
if (data == 'true') {
window.location.href="thankyou.php";
};
if (data !== 'true') {
$("#status").html(data);

};
},
error: function(){
}
});
}));
});

<form id="frmContact" action="" method="post">
<div id="status"></div>
<div>
<label>Email</label>
<span id="userEmail-info" class="info"></span><br/>
<input type="text" name="userEmail" id="userEmail" class="demoInputBox">
</div>
<div>
<input type="submit" value="Send" class="btnAction" />
</div>
</form>



数据.php

<?php

// PHP code above...
//Lets add $error variable for test purpose...

$error = 'Invalid data';

?>

最佳答案

仅更改成功函数,如下所示

success: function(data){
if (data === 'Invalid data') {
$("#status").html(data);
}
else {
window.location.href="thankyou.php";
}
}

在 php 中你应该 echo $error

关于javascript - php post 返回 true 或无错误后 AJAX 重定向,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32779966/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com