作者:Hancl | 来源:互联网 | 2023-09-25 10:43
我找不到解决这个访问通过AJAX传递给我的PHP脚本的变量的简单问题的解决方案.我甚至尝试过isset($_POST),但仍然无法找到用户名和密码变量.这是AJAX调用:
我找不到解决这个访问通过AJAX传递给我的PHP脚本的变量的简单问题的解决方案.我甚至尝试过isset($_ POST),但仍然无法找到用户名和密码变量.
这是AJAX调用:
var u = $("#username", form).val();
var p = $("#password", form).val();
//testing
console.log('Username: '+u); // 'John'
console.log('Password: '+p); // 'test'
if(u !== '' && p!=='') {
$.ajax({url: 'http://www.domain.net/php/user-login.php',
data: {username:u,password:p},
type: 'post',
async: true,
dataType:'json',
beforeSend: function() {
// This callback function will trigger before data is sent
$.mobile.loading('show'); // This will show ajax spinner
},
complete: function() {
// This callback function will trigger on data sent/received complete
$.mobile.loading('hide'); // This will hide ajax spinner
},
success: function (data) {
//save returned data to localStorage for manual button toggling later
//window.localStorage.setItem('topGenderDataArray',data);
console.log("Login successful: "+ data);
console.dir(data);
alert("Welcome back "+data['username']);
$("#loginButton").removeAttr("disabled");
},
error: function (xhr,request,error) {
// This callback function will trigger on unsuccessful action
alert('Network error has occurred please try again! '+xhr+ " | "+request+" | "+error);
}
});
这是PHP脚本的开头:
if(isset($_POST['username']) && isset($_POST['password']))
{
$data['username'] = $_POST['username'];
$data['password'] = $_POST['password'];
}
else{
$data['message']= "Sorry, an error occurred! []";
$data['user_id']= -1;
echo json_encode($data);
exit();
}
解决方法:
问题出在你的PHP代码中
你在else子句中执行echo json_encode($data),而你应该在if之后执行它,就像这样:
if(isset($_POST['username']) && isset($_POST['password']))
{
$data['username'] = $_POST['username'];
$data['password'] = $_POST['password'];
}
else
{
$data['message']= "Sorry, an error occurred! []";
$data['user_id']= -1;
}
echo json_encode($data);