如何解决从php成功响应后,Ajax不重定向
用户凭据验证完成后,我正尝试从登录页面重定向到首页。响应工作正常。获得成功的响应后,我想重定向到“主页”。我在客户端使用Javascript,在服务器端使用PHP。但是成功的响应并没有达到ajax。
Ajax调用
$('#login-btn').click(function(e) {
if ($('#login-form')[0].checkValidity()) {
e.preventDefault();
$("#login-btn").html('<img src="images/tra.gif" /> Please Wailt..');
if ($('#Lemail').val() == '') {
$('#error-message').fadeIn().html('* Email is Required!');
setTimeout(function() {
$('#error-message').fadeOut('slow');
},5000);
} else if ($('#Lpassword').val() == '') {
$('#error-message').fadeIn().html('* Please enter password!');
setTimeout(function() {
$('#error-message').fadeOut('slow');
},5000);
} else {
$('#error-message').text('');
$.ajax({
url: 'actionlog.php',method: 'POST',data: $('#login-form').serialize() + '&action=login',success: function(response) {
if (response === 'true') {
window.location = '../';
} else {
$('#logAlert').html(response);
}
}
});
}
}
});
});
PHP代码:
<?php
//Login Request
if (isset($_POST['action']) && $_POST['action'] == 'login') {
if (Input::exists()) {
$validate = new Validate();
$validation = $validate->check($_POST,array(
'email' => array('required' => true),'password' => array('required' => true)
));
if ($validation->passed()) {
$user = new User();
//create Remember
$remember = (Input::get('remember') === 'on') ? true : false;
$login = $user->login(Input::get('email'),Input::get('password'),$remember);
if ($login) {
echo 'true';
}
}else{
foreach ($validation->errors() as $error) {
$user = new User();
echo $user->showMessage('danger',$error);
}
}
}
}
请帮助我
解决方法
您必须调整您的响应。...有时从服务器收到的字符串包含空格.....这会导致问题无法重定向到其他页面。
$.ajax({
url: 'actionlog.php',method: 'POST',data: $('#login-form').serialize() + '&action=login',success: function(response) {
if ($.trim(response) === 'true') {
window.location = '../';
} else {
$('#logAlert').html(response);
}
}
});
,
尝试通过这种方式做到这一点:
$.ajax({
type: "POST",url: 'actionlog.php',data: $('#login-form').serialize()+'&action=login',dataType: 'json',beforeSend: function(){},success: function(response){
window.location.href = '/';
},error: function(){
console.log('You got an error');
}
});
如果您从服务器获得成功的响应,则应该可以正常工作。此示例表明服务器将返回 json ,但您可以指定自己喜欢的任何内容。
UPD:我不好。您可以同时使用 window.location 和 window.location.href 。另外,在上面的示例中,我删除了选项
processData: false,contentType: false,
因为当您发送 FormData 时会使用它们。您可能需要考虑使用 FormData 并将其传递给 data :),这在发送带有文件的表单时非常有用
使用 FormData ,它将看起来像这样:
$(document).on('submit','.your-form-selector',function(e){
e.preventDefault();
var data = new FormData(this); // "this" is your form and includes all the form fields
$.ajax({
type: "POST",data: data,// FormData goes here
dataType: 'json',processData: false,success: function(response){
window.location.href = '/';
},error: function(){
console.log('You got an error');
}
});
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。