我是javascript的新手。我希望当用户在注册时输入用户名并且该名称已存在于数据库中时,我将显示Name already exists
的提示。你需要输入另一个用户名。
现在我想在同一个提示框中点击一个按钮,用户将再次被重定向到注册页面signup.html
。
我无法弄清楚如何做到这一点。 我所做的就是这个---
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<script>
prompt("Username already exists\n please enter another username");
</script>
</body>
</html>
答案 0 :(得分:3)
https://developer.mozilla.org/en-US/docs/Web/API/Window/location
你可以把它放在你喜欢的任何js-script块中。例如
<script>
function redirectMe(url){
window.location = url;
}
setTimeout(redirectMe('http://stackoverflow.com'}, 3000);
</script>
将在3000ms(= 3s)之后重定向到stackoverflow
答案 1 :(得分:1)
答案 2 :(得分:1)
要检查用户是否已存在于数据库中,您必须制作一些服务器端代码,而不仅仅是javascript(客户端)。
您必须使用AJAX来调用服务器脚本(例如,在PHP或ASP中),发送用户输入的名称。服务器端脚本将通过进行SQL查询来检查数据库,如果是,则返回其对javascript的响应。
以下是使用jQuery的示例:
HTML
Your name : <input type="text" id="username" />
<button id="myButton" value="check if user exists" />
<强> JAVASCRIPT 强>
<script src="https://code.jquery.com/jquery-2.1.3.min.js" type="text/javascript"></script>
<script>
$(function () {
//when you will click on your button
$('#myButton').click(function(){
//get prompted username
var username = $('#username').val();
//check if username exists making AJAX call
checkUserName(username);
});
});
function checkUserName(name)
{
//ajax call to your server-side script
$.ajax({
url: 'myscript.php',
type: 'POST',
data: 'username='+name,
success: function (response) {
//if response is 1, a user with this name already exists
if(response == 1)
{
alert('user already exists');
}
//the name is available
else
{
//redirect to your "signup.html" page
window.location.href="signup.html"
alert('name is available');
}
}
});
}
</script>
<强> PHP 强>
myscript.php
<?php
//you have to secure and check the variable, depending what you will use, mysqli_real_escape_string, or escape properly the received variables
$username = $_POST['username'];
//query example, you have to ajust depending on your database & user table
$sql = 'SELECT COUNT(username) FROM db.user WHERE username = "'.$username.'"';
//exec your query
//if the count returned result is > 0, there is a user with this name, return 1 for example
//else, user with this name does not exist, return 0 for example
if($return == 1)
echo "1";
else
echo "0";
exit;
这是主要的想法:)尝试制作一个JSFiddle代码并尝试使用它,如果你有更多的问题,请写在这里!
的问候,
于连