这是php中的代码
<?php session_start();
//Connect to database from here
$link = mysql_connect('****', '****', '****');
if (!$link) {
die('Could not connect: ' . mysql_error());
}
//select the database | Change the name of database from here
mysql_select_db('****');
//get the posted values
$user_name=htmlspecialchars($_GET['user_name'],ENT_QUOTES);
$pass=$_GET['password'];
//now validating the username and password
$sql="SELECT user_name, password FROM tbl_user WHERE user_name='".$user_name."'";
$result=mysql_query($sql);
$row=mysql_fetch_array($result);
//if username exists
if(mysql_num_rows($result)>0)
{
//compare the password
if(strcmp($row['password'],$pass)==0)
{
// Return success message
$message = array("flag" => "1", "msg" => "Login successfully.");
echo json_encode($message);
//Regenerate session ID to prevent session fixation attacks
//session_regenerate_id();
//now set the session from here if needed
//$_SESSION['u_name']=$user_name;
//$member=mysql_fetch_assoc($result);
//$_SESSION['u_id']=$member['id'];
//$name_show=$member['first_name'].' '.$member['last_name'];
//$_SESSION['name']=$name_show;
//Write session to disc
//session_write_close();
}
else
// Return error message
$message = array("flag" => "0", "msg" => "Incorrect password.");
echo json_encode($message);
}
else //if username not exists
{ // Return error message
$message = array("flag" => "0", "msg" => "Incorrect id.");
echo json_encode($message);
}
mysql_close($link);
?>
这是html中的代码
$.ajax({
type: "get",
url: "http://mydomain.com/ajax_login.php",
data: {
user_name: $("#username").val(),
password: $("#password").val()
},
success: function(jsondata){
if (jsondata.flag == "0"){
//if flag is 0, indicate login fail
}
else {
//if flag is 1, indicate login success and redirect to another page
window.location.href = 'ABC.html';
}
},
datatype: "json"
});
显示屏显示"{\"flag\":\"0\",\"msg\":\"Incorrect id.\"}"
我的问题是,现在即使旗帜为0,它仍然会转到ABC.html if子句应该被修改为什么,如果该标志为0,它仍将在该子句的真实部分?
编辑这是编码的更多细节
答案 0 :(得分:1)
或许jsondata.flag
未定义
您需要解码响应字符串以将其用作JS对象
或者设置dataType : 'json'
...
答案 1 :(得分:1)
请务必在jQuery ajax方法中使用dataType: "json"
配置ajax调用,并确保在PHP响应中发送JSON标头,如。
header("Cache-Control: no-cache, must-revalidate");
header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
header("Content-type: application/json");
echo json_encode($yourArray);
如果你没有正确配置你的ajax调用,结果可能被解释为一个简单的字符串。