Php 检查用户名jqueryajax
我有以下ajax调用Php 检查用户名jqueryajax,php,jquery,Php,Jquery,我有以下ajax调用 $.ajax( { type: "POST", url: "Utilities/CheckUsername.php", data: "un="+ un, success: function(data) { if(data!=1)
$.ajax(
{
type: "POST",
url: "Utilities/CheckUsername.php",
data: "un="+ un,
success: function(data)
{
if(data!=1)
{
$('#mike').html(data);
return false;
}
}
});
如果使用用户名,我希望页面保持不变,否则重定向到for的action属性中的内容
显然这不起作用。但是为什么呢?我不想使用preventdefault
,这样我可以更好地了解问题所在和解决方案
编辑:
服务器代码
<?php
$seed = 'n48sma94r98';
$email = $_POST['un'];
$mysqli = new mysqli('localhost','uml','uml','uml');
if (!$mysqli)
{
printf("Can't connect to MySQL Server. Errorcode: %s\n", mysqli_connect_error());
exit;
}
$query = "Select User_Email as Email from user2 where User_Email = AES_ENCRYPT('$email','$seed') ";
$result = $mysqli->query($query);
if($result->num_rows > 0)
{
echo "1";
}
else
{
echo "2";
}
?>
一些建议。命名变量和方法。什么是“联合国”和“数据”?它们包含什么 还返回什么类型的数据?字符串、HTML、XML、JSON 如果要重定向,可以使用
window.location='someURL'代码>
要发送表单,可以执行以下操作:$(“#表单id”).submit()代码>
您可以返回更有意义的消息,如usernameExists、usernameFound或usernameNotExists、usernameNotFound。即使你是唯一一个在这个项目上工作的人,当你四处寻求帮助时,peep也需要理解你的代码。它应该读起来像句子。我想你应该用
if(data!=1)
查看用户名是否已被使用
您是否尝试使用某种调试器查看数据的值?(甚至是警报()
)
由于我假设您在用户名已被使用时没有从服务器发送1
。我通常使用OK
作为响应指示符(或您所称的任何指示符)。如果响应(您的数据
)以确定
开头,则为肯定,否则整个消息为错误:
在Javascript中:
success: function(response) {
if ( 'OK' == response.substr(0, 2) ) {
// Okay, so show something green or do nothing
var message = response.substr(2); // Everything after "OK"
}
else {
// Not okay, so show something red or redirect
var goto = response;
// The entire response message `response` is the target destination
// If you don't want PHP to define the redirect location, just hard code it right here
window.location = goto;
}
}
在PHP中:
$result = $mysqli->query($query);
$usernameExists = $result->num_rows > 0; // A nice boolean
exit( $usernameExists ? '/error.html' : 'OKThis username is fine' );
PS。success
函数中的return false
不起任何作用。你可以忽略这一点
编辑
在不更改PHP的情况下:
success: function(response) {
if ( '1' !== response ) {
window.location = 'error.html';
}
}
因为response
是一个字符串,所以我要检查它(而不是数字)。检查相同性(==
)而不是相等性(=
)也不会有什么坏处。您可能应该添加更多的代码,以便我们了解您正在尝试做什么。这是在表单.submit()上执行的吗?还显示一些服务器端代码,以显示在已使用用户名(un
?)时返回的响应。如果您编写有意义的变量名,会容易得多。echo 1和echo 2也不需要引号,但是这是一个糟糕的想法,您可以返回更有意义的消息,如usernameExists、usernameFound或usernameNotExists、usernameNotFound。即使你是唯一一个在这个项目上工作的人,当你四处寻求帮助时,peeps也需要理解你的代码。它应该读起来像句子一样。单击登录按钮后,$(“#mike')
中的值是多少?窗口。没有s
的位置
如果用户名不存在,数据变量显示为2,如果用户名不存在,则显示为1。(php工作)如果是1,我想重定向到另一个页面,如果是2,他们必须尝试其他用户名。这就是我需要帮助的地方。
success: function(response) {
if ( '1' !== response ) {
window.location = 'error.html';
}
}