Jquery post方法不起作用

时间:2014-04-05 11:00:53

标签: php jquery post

我正在使用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');
            }
        });
    });
});

用户名值为的文件checkname.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);

但是它不会回显成功或失败消息,页面只是加载文本框中的值reset.i也检查了php文件及其工作正常。任何帮助?

2 个答案:

答案 0 :(得分:2)

看起来问题是您的点击操作正在触发页面重新加载,例如表单提交或锚点击。因此,请阻止处理程序中的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');
        }
    });
});

答案 1 :(得分:0)

您可以做的是首先将按钮类型从提交更改为按钮,以便点击您的表单时,无需点击按钮提交。

然后根据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');
    }
    });
});
相关问题