如何在 jQuery Ajax 调用后处理重定向请求
我有一个通过Jquery进行客户端验证的表单。然后,Jquery将此数据传递给php脚本进行服务器端验证。在php脚本的末尾,当成功时我尝试重定向,但没有重定向发生。
Jquery是否干扰了重定向?如何让php脚本进行重定向。我不想使用jquery进行重定向,因为我要使用会话,并希望在重定向时保留会话数据。
这是代码:
JQUERY:
$.ajax({
//this is the php file that processes the data and send mail
url: "includes/process/processAdminLogin.php",
//POST method is used
type: "POST",
//pass the data
data: dataString,
//indicate result is text
dataType: "text",
//Do not cache the page
cache: false,
//success
success: function (data) {
$('input').removeAttr('disabled'); //enable input fields again.
if(data == "fail"){
$("#statusMessage").html("");
$("#statusMessage").html("<p class='statusBoxWarning'>Username and password do not match!</p>");
$('button').removeAttr('disabled');
document.forms[0].reset();
}
}
});
PHP
if($correctPass == 1){
ob_start();
session_start();
$_SESSION['usernameIdentity'] = $userName;
unset($userName, $userPass);
header("Location: ../../adminDashboard.html");
exit;
}else{
echo "fail";
}
这个 PHP 脚本到了重定向部分就卡住了。我希望保留 jQuery 功能和 PHP 重定向,有更好的方法吗?
谢谢!
FINAL WORKING SOLUTION:
好的,经过本帖和其他类似帖子的意见反馈后,这是我现在得到的工作解决方案。它可能不是最有效或最美观的解决方案,但它能正常工作,现在必须这样做。
JQUERY
$.ajax({
//this is the php file that processes the data and send mail
url: "includes/process/processAdminLogin.php",
//GET method is used
type: "POST",
//pass the data
data: dataString,
//indicate result is text
dataType: "text",
//Do not cache the page
cache: false,
//success
success: function (data) {
$('input').removeAttr('disabled'); //enable input fields again.
if(data == "success"){
$('#statusMessage').html('<form action="http://www.example.com/test/userRegistration/adminDashboard.html" name="userSubscription" method="post" style="display:none;"><input type="text" name="username" value="' + reg_contact_username + '" /><input type="text" name="password" value="' + reg_contact_password + '" /></form>');
document.forms['userSubscription'].submit();
}else{alert("couldn t redirect");}
}
});
PHP
if($correctPass == 1){
echo "success";
}else{
echo "fail";
}
接收重定向页面将不得不再次验证用户名和密码,因此验证将进行2次...这真的很低效。如果有人能为我提供更好的解决方案-拜托了!一个样例会帮助我更好地理解。
谢谢!
stdClass
对象,然后使用json_encode
将它们转换为漂亮的JavaScript对象在前端显示。 - rockerest