我是jQuery和 AJAX 的新手,我正在做一个登录页面的项目,我需要使用AJAX从数据库中检索数据。我不是100%流利的英语,所以我会尽我所能来解释这个问题(在谷歌翻译的帮助下)。下面是我使用的代码:index.html
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
</head>
<body>
<form validate="">
<input type="text" placeholder="Username" id="username" required/><br />
<input type="password" placeholder="Password" id="password" required/><br />
<input type="submit" id="submit" value="Login" />
</form>
<script type="text/javascript">
// when document is loaded
$(document).ready (
// when submit is clicked
$("#submit").click (
// sets test to null
var test = null;
// sets username to value of username input
var username = document.getElementById("username").value;
// AJAX request
$.ajax({
type: "POST",
async: true,
url: test.php,
data: {username: username},
success: function (data) {
test = data;
console.log(test);
return test;
}
});
);
);
</script>
</body>
</html>
test.php
<?php
// connects to database
$conn = mysqli_connect('server', 'username', 'password', 'database');
// sets var username to POST username value
$username = $_POST['username'];
// SQL Query
$sql = "SELECT * FROM users WHERE username='" . $username . "'";
$result = mysqli_query($conn, $sql);
// sets result to mysqli_fetch_assoc()
$result = mysqli_fetch_assoc( $result );
// echos $result
echo $result['password'];
// closes database connection
mysqli_close( $conn );
?>
控制台日志
控制台输出:
[DOM] Input elements should have autocomplete attributes (suggested: "current-password"): (More info: https://www.googlesite.com)
<input type="password" placeholder="Password" id="password" required>
Uncaught SyntaxError: Unexpected token var ajax.html:19
我看了代码,似乎找不到错误。先谢谢你了!;)
2条答案
按热度按时间xbp102n01#
你可以使用
submit
事件代替click
事件。在您的情况下,只需将
id
输入到form
,如下所示-现在,在您的
js
脚本中-所以检查你的整个代码-
希望这对你有帮助。
pcrecxhr2#
您需要向document.ready()调用和click()调用传递一个函数。