0
我目前使用Slim和Ajax來開發移動應用程序。在我的數據庫中,我有一個存儲登錄會話代碼的列。我需要能夠登錄後,將輸入的用戶名與數據庫進行比較,並根據該用戶名檢索sessionCode。在登錄過程中檢索數據庫數據
我當前的PHP是這樣的:
$app->post('/logIn/', 'logIn');
function logIn()
{
$request = \Slim\Slim::getInstance()->request();
$q = json_decode($request->getBody());
//$hashedPassword = password_hash($q->password, PASSWORD_BCRYPT);
$sql = "SELECT * FROM users where username=:username AND password=:password";
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam("username", $q->username);
$stmt->bindParam("password", $q->password);
$stmt->execute();
//$row=$stmt->fetch(PDO::FETCH_ASSOC);
$row=$stmt->fetch(PDO::FETCH_OBJ);
//$verify = password_verify($q->password, $row['password']);
$db = null;
echo json_encode($row);
} catch (PDOException $e) {
echo $e->getMessage();
}
} //PHP 5.4 LogIn
$app->get('/getSessionCode/:username','getSessionCode');
function getSessionCode($username)
{
$request = \Slim\Slim::getInstance()->request();
$q = json_decode($request->getBody());
$sql = "SELECT * FROM users WHERE username=:username";
try{
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam("username", $username);
$stmt->execute();
$row=$stmt->fetchALL(PDO::FETCH_OBJ);
$dbh=null;
echo json_encode($row);
}
catch(PDOException $e){
if(db != null) $db = null;
echo $e->getMessage();
}
}
Ajax代碼:
$("#checkLogIn").click(function()
{
username = $("#enterUser").val();
$.ajax({
type: 'POST',
contentType: 'application/json',
url: rootURL + '/logIn/',
dataType: "json",
data: checkLogIn(),
success: function(data)
{
if(data != false)
{
$.ajax({
type: 'GET',
url: rootURL + "/getSessionCode/" + username,
dataType: "json",
success: sessionData
});
}
else
{
alert("Username and/or Password was incorrect");
}
}
})
});
function checkLogIn(data)
{
return JSON.stringify({
"username": $("#enterUser").val(),
"password": $("#enterPass").val(),
});
}
function sessionData(data){
session = data.sessionCode;
alert(username);
alert(session);
$.mobile.changePage("#mainMenu");
}
當我運行應用程序並登錄它運行雖然沒有問題,但是當它到達警報(會話),它返回undefined。我將會話和用戶名都設置爲全局變量,因此這不是問題,當它達到alert(用戶名)時,它會返回我輸入的用戶名。
你能讀懂什麼是Ajax調用的響應來解決我的問題?您可以使用瀏覽器控制檯進行此操作。 –
我解決了這個問題。我想我應該爲任何可能需要幫助的人添加一個答案 – John