send()之后xhttp.open()onreadystatechange不触发而没有警报

时间:2019-07-09 13:56:57

标签: javascript asynchronous xmlhttprequest

我正在尝试从服务器中获取json字符串并进行解析。一切正常,除了onreadystatechange仅在.send()方法之后发出警报时才触发。如果没有警报,服务器将不会总是收到“ GET”请求。我发现解决问题的唯一方法是在open()上将异步设置为false。我希望代码是异步编写的。

function collectData(){
    var user = document.forms["search"]["user"].value;
    if (user !== ""){
        var url = 'http://localhost:3000/users/'.concat('', user);
        var xhttp;
        if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
            xhttp=new XMLHttpRequest();
        }
        else{// code for IE6, IE5
            xhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }
        xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && (this.status == 200 || this.status == 304)) {
                var response = JSON.parse(xhttp.responseText);
                alert(response.data[0].id);
            }
        };
        xhttp.open("GET", url, true);
        xhttp.send();
        alert(url);
    } else {
        alert("Name must be filled out");
        return false;
    }
}

我只想能够提醒response.data [0] .id

编辑:添加更多代码以重新创建方案。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="css/main.css">
    <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
    <script src="js/script.js"></script>
    <title>Exsisting Customer</title>
</head>
<body>
    <form name="search" onsubmit="return collectData()">
        Search customer:<br>
        <input type="text" name="user"><br>
        <input type="submit" value="Submit">
    </form>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

您正在提交表单,因此onsubmit功能完成后,浏览器便开始导航到新页面。这可能会完全取消Ajax请求,但如果没有取消,则肯定会破坏正在等待响应的JavaScript环境。

您需要留在同一页面上以使用JS处理响应。

使用当前采用的方法,您应该return false中的collectData。您应该考虑使用现代JS,并使用addEventListenerevent.preventDefault