如何在keyup上传递两个变量?

时间:2014-09-16 23:04:29

标签: javascript php ajax

坚持这一个。我想在"用户名"的密钥上传递2个表单输入。我想发送"用户名"和"位置"输入到我的PHP。可以这样做吗?尝试了一些事情,但无法弄清楚。

注意:当输入"用户名"时,我想传两个。

形式:

<fieldset>
<input name="location" type="text" id="location" maxlength="15">
<label for="username">Enter Username :                                                                 
<input name="username" type="text" id="username" maxlength="15">                            
<span id="user-result"></span>                                      
</label>                                                                    
</div>                                                              
</fieldset>

脚本:

$(document).ready(function() {
    $("#username").keyup(function (e) {

        //removes spaces from username
        //$(this).val($(this).val().replace(/\s/g, ''));
        var username = $(this).val();
        if(username.length < 4){$("#user-result").html('');return;}

        if(username.length >= 4){
            $("#user-result").html('<img src="../images/ajax-loader.gif" />');
            $.post('check.php', {'username':username}, function(data) {
              $("#user-result").html(data);
            });
        }
    }); 
});

2 个答案:

答案 0 :(得分:2)

只需从用户名keyup事件处理程序中获取位置输入的值,并将其与请求一起传递:

$(document).ready(function() {
    $("#username").keyup(function (e) {

        //removes spaces from username
        //$(this).val($(this).val().replace(/\s/g, ''));

        var username = $(this).val();
        var location = $('#location').val();

        if(username.length < 4){$("#user-result").html('');return;}

        if(username.length >= 4){
            $("#user-result").html('<img src="../images/ajax-loader.gif" />');
            $.post('check.php', { 'username':username, 'location': location}, function(data) {
              $("#user-result").html(data);
            });
        }
    }); 
});

答案 1 :(得分:1)

$("#username").on('keyup', function (e) {
        // grab the elements we're interested in
        var username = $(this).val(),
            location = $("#location").val();

        if (username.length > 3) {
            $.ajax({
                url: 'check.php',
                type: 'POST',
                data: {
                    username: username,
                    location: location
                },
                success: function (data) {
                    // do something after success
                    console.log(data)
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    // deal with the error
                    console.log('status: ' + textStatus);
                    console.log('error: ' + errorThrown);
                },
                dataType: 'json' // or change to whatever you want
            });
        }
    });