AJAX适用于jQuery,但不适用于vanilla JS

时间:2016-10-22 09:18:15

标签: javascript jquery ajax

我有一个小表单,当用户名字段模糊或失焦时,AJAX会检查输入的用户名是否已记录在数据库中。问题是jQuery中的AJAX可以工作,但不能用于vanilla JS。我需要知道我的代码的哪一行或哪一部分我弄错了。

HTML

<form action="process.php" method="post">
    <input class="username" type="text" name="username" placeholder="Enter username" autocomplete="off">
    <span class="uname_notice"></span><br>
    <input type="submit" value="Submit">
</form>

的jQuery

$('.username').blur(function() {
    var username = $(this).val();

    $.ajax({
        url: 'process.php',
        type: 'post',
        data: {username: username},
        success: function(responseText) {
            $('.uname_notice').text(responseText);
        }
    })
});

Vanilla JS

document.querySelector('.username').onblur = function() {
    var xhr = new XMLHttpRequest();

    xhr.open("POST", "process.php", true);
    xhr.onreadystatechange = function() {
        if(xhr.readyState == 4 && xhr.status == 200) {
            document.querySelector('.uname_notice').textContent = xhr.responseText;
        }
    }
    xhr.send();
}

2 个答案:

答案 0 :(得分:0)

与HTTP请求一起发送数据。

document.querySelector('.username').onblur = function() {
    var xhr = new XMLHttpRequest();

    var data = new FormData();
    var username = document.getElementsByClassName('username')[0].value;
    data.append('username', username);
    xhr.open("POST", "process.php", true);
    xhr.onreadystatechange = function() {
        if(xhr.readyState == 4 && xhr.status == 200) {
            document.querySelector('.uname_notice').textContent = xhr.responseText;
        }
    }
    xhr.send(data);
}

答案 1 :(得分:0)

您忘了指定帖子值。试着用这个:

document.querySelector('.username').onblur = function() {

    var params = 'username='+this.value;

    var xhr = new XMLHttpRequest();

    xhr.open("POST", "process.php", true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;");
    xhr.setRequestHeader("Content-length", params.length);
    xhr.setRequestHeader("Connection", "close");
    xhr.onreadystatechange = function() {
        if(xhr.readyState == 4 && xhr.status == 200) {
            document.querySelector('.uname_notice').textContent = xhr.responseText;
        }
    };
    xhr.send(params);
};