我正在使用jquery来检查用户输入的名称是否已存在于数据库中,如图所示。我的表格:
<tr>
<td>Username:</td>
<td><input type="text" name="us" size="38" id="name"></br>
<span id="usmsg" class="msg">Username already exists!</span>
</td>
</tr>
Jquery 脚本:
$(document).ready(function(){
$('#usmsg').hide();
$('#addc').click(function(event){
var us=$('#name').val();
alert(us); //just to check this code is executed or not.
$.post('checkname.php', {'myuser' : us}, function(data) {
if(data=='exist') {
alert('success');
}
else {
alert('failure');
}
});
});
});
文件校验名称.php用户名的值在哪里:
<?php include("includes/connection.php");?>
<?php
$myuser = $_POST['myuser'];
$qry = "select username from users where username='$myuser'";
$res = $con->query($qry);
$r = $res->num_rows;
if($r>0)
echo 'exist';
else
echo 'notexist';
?>
问题是它根据代码正确提醒我用户名
alert(us);
但是它不会回显成功或失败消息,页面只是加载文本框重置中的值.我还检查了 PHP 文件及其工作正常。有什么帮助吗?
看起来问题是您的点击操作触发了页面重新加载,例如表单提交或锚点点击。因此,请阻止处理程序中 click 事件的默认操作。
由于您的点击操作正在触发页面加载,因此它不会等待 ajax 回调执行,因为 alert() 没有出现。
$('#addc').click(function (event) {
//prevent the default action of the click like form submit
event.preventDefault();
var us = $('#name').val();
alert(us); //just to check this code is executed or not.
$.post('checkname.php', {
'myuser': us
}, function (data) {
if (data == 'exist') {
alert('success');
} else {
alert('failure');
}
});
});
您可以做的是首先将按钮类型从"提交"更改为"按钮",以便在单击按钮时不会提交表单。
然后根据Ajax回复,您可以提交如下表单:
$('#addc').click(function() {
//prevent the default action of the click like form submit
var us = $('#name').val();
alert(us); //just to check this code is executed or not.
$.post('checkname.php', {
'myuser': us
}, function(data) {
if ($.trim(data) === 'exist') {
alert('success');
// This line will submit the form.
$('form').submit();
} else {
alert('failure');
}
});
});