ajax调用不使用双数据参数

时间:2014-09-27 23:22:55

标签: javascript php jquery ajax json

这是我下面的ajax代码

$('.username-check').on('click', function() {
    //console.log('You clicked');
    alert(username);
    var username = $('.username-target'),
        lastname = $('.lastname-target'),
        feedback = $('.username-feedback');

    function changeFeednackText(text){ feedback.text(text); }

    function couldNotCheck(){ changeFeednackText('Could not check at this time'); }

    $.ajax({
        url: 'check/username.php',
        type: 'get',
        data: {
            username: username.val(),
            lastname: lastname.val()
        },
        dataType: 'json',
        success: function(data){
            if(data.available !== undefined){
                if(data.available === true){
                    changeFeednackText('That username is available.');
                }else{
                    changeFeednackText('Sorry, that username is not available.');
                }
            }else{
                couldNotCheck();
            }
        },
        error: function(){
            couldNotCheck();
        }
    });
});

我的HTML代码

<form action="signup.php" method="post" autocomplete="off">
    <div>
        <label for="username">First Name<input type="text" name="username" id="username" class="username-target"></label><br />
        <label for="lastname">Last Name<input type="text" name="lastname" id="lastname" class="lastname-target"></label><br />
        <a href="javascript:;" class="username-check">Check username</a>
    </div>
    <div class="username-feedback"></div>
    <div><input type="submit" value="Check"></div>
</form>

我的PHP也低于

header('Content-Type: application/json');
$username = (isset($_GET['username'])) ? htmlspecialchars($_GET['username']) : null;
$lastname = (isset($_GET['lastname'])) ? htmlspecialchars($_GET['lastname']) : null;

$available = true;
if($username == 'bar' && $lastname == 'foo'){
// if($username == 'bar'){
    $available = false;
}
$arr = array('username' => $username . $lastname, 'available' => $available);
echo json_encode($arr);

如果我使用if false这样的if语句,上面的代码工作正常并返回if($username == 'bar'){但是当我使用if($username == 'bar' && $lastname == 'foo'){这两个值时,它总是返回true }。

请注意,我已尝试将foo和bar分别设为usernamelastname以获得false回拨但未成功。不知道这里有什么问题,但我希望你们中的任何人能够发现错误并帮助我......你有什么想法吗?

1 个答案:

答案 0 :(得分:1)

尝试改变:

 if(data.available !== undefined){

 if( typeof(data.available) != "undefined" ) {

在你的成功功能中。