gpt4 book ai didi

javascript - jquery ajax html 警报中的 "\r\n\"

转载 作者:行者123 更新时间:2023-11-28 07:37:49 24 4
gpt4 key购买 nike

我有一个如下所示的 ajax 请求

$(document).ready(function() {
$(document).on('click', '#submit', function() {
var UserName = $('#username').val();
var PassWord = $('#password').val();
console.log(UserName);
$.ajax({
type: 'POST',
url: 'ajax/Login.php',
dataType: "text",
data: {
username: UserName,
password: PassWord
},
success: function(data) {
alert(JSON.stringify(data));
window.location='pages/mainpage.php';
},
error: function(data) {
alert('Login Error');
//window.location='../index.php';
}
});
});
});

我的 php 是这样的

$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);

if (isset($username)) {
$stmt = $dbh->prepare("SELECT * FROM userlist_tbl WHERE username = ? ");
$stmt->bindValue(1, $username);
$stmt->execute();
$selected_row = $stmt->fetch(PDO::FETCH_ASSOC);
if ($selected_row['username'] === $username) {
if ($selected_row['password'] === $password) {
$_SESSION['login_user'] = $username;
echo "Welcome ".$username;
}else{
echo "Password incorrect";
}
}
}else{
echo "Username is empty";
}

当我没有在用户名中输入任何内容时,我希望警报将是用户名为空,与密码为空时相同,警报应该是密码不正确,但我得到了"\r\n\" 但如果在用户名中输入一些像 John 的内容,它会提醒 Welcome John"\r\n\" 为什么是发生这种情况?当用户名与密码相同时,如何让它提醒用户名为空?任何想法都被接受..

最佳答案

试试这个:在ajax部分,dataType: "text",更改为dataType: "json",并且服务器php代码是以下:可能有效

  //put this function top of this page
ob_start();

$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$json="";
if (isset($username)) {


$stmt = $dbh->prepare("SELECT * FROM userlist_tbl WHERE username = ? ");
$stmt->bindValue(1, $username);
$stmt->execute();
$selected_row = $stmt->fetch(PDO::FETCH_ASSOC);
if ($selected_row['username'] === $username) {
if ($selected_row['password'] === $password) {
$_SESSION['login_user'] = $username;
$json.="Welcome ".$username;
}else{
$json.="Password incorrect";
}
}
}else{
$json.="Username is empty";
}
ob_end_clean();
echo json_encode($json);

?>

关于javascript - jquery ajax html 警报中的 "\r\n\",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28404780/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com