我有Ajax登录提交,工作得很好。现在我需要在成功时将$ user_id发送回登录页面。但无法弄清楚如何。
以下是我所拥有的。
这是php页面
<?
if (!securePage($_SERVER['PHP_SELF'])){die();}
//Prevent the user visiting the logged in page if he/she is already logged in
if(isUserLoggedIn()) { header("Location: account.php"); die(); }
//Forms posted
if(!empty($_POST))
{
$errors = array();
$username = sanitize(trim($_POST["user"]));
$password = trim($_POST["password"]);
//Perform some validation
//Feel free to edit / change as required
if($username == "")
{
$response['success'] = false;
}
if($password == "")
{
$response['success'] = false;
}
if(count($errors) == 0)
{
//A security note here, never tell the user which credential was incorrect
if(!usernameExists($username))
{
$response['success'] = false;
}
else
{
$userdetails = fetchUserDetails($username);
//See if the user's account is activated
if($userdetails["active"]==0)
{
$response['success'] = false;
}
else
{
//Hash the password and use the salt from the database to compare the password.
$entered_pass = generateHash($password,$userdetails["password"]);
if($entered_pass != $userdetails["password"])
{
//Again, we know the password is at fault here, but lets not give away the combination incase of someone bruteforcing
$response['success'] = false;
}
else
{
//Passwords match! we're good to go'
$response['success'] = true;
}
}
}
}
}
//$user_id = $loggedInUser->user_id;
echo json_encode($response);
?>
这是调用php页面的ajax。还有我需要从php页面检索ID的地方。
<script type="text/javascript">
//login ajax to send over user and pass LS
function handleLogin() {
var form = $("#loginForm");
//disable the button so we can't resubmit while we wait
$("#submitButton",form).attr("disabled","disabled");
var e = $("#user", form).val();
var p = $("#password", form).val();
console.log("click");
if(e != "" && p != "") {
var str = form.serialize();
//McDOn(str);
$.ajax({
type: 'POST',
url: 'http://vsag.actualizevps.com/loginmobile.php',
crossDomain: true,
data: {user: e, password :p},
dataType: 'json',
async: false,
success: function (response){
//alert ("response");
if (response.success) {
//alert("you're logged in");
window.localStorage["user"] = e;
//window.localStorage["password"] = md5(p);
//window.localStorage["UID"] = data.uid;
window.location = "create.html";
}
else {
alert("Your login failed");
//window.location("main.html");
location.reload();
}
},
error: function(error){
//alert(response.success);
alert('Could not connect to the database' + error);
window.location = "main.html";
}
});
}
else {
//if the email and password is empty
alert("You must enter user and password");
}
return false;
}
</script>
答案 0 :(得分:0)
此时$ response值只是true或false,你可以返回一个数组:
$response = array("Success" => true, "UserId" => $user_id);
和你的AJAX响应,响应变量
response.UserId
将包含用户ID