【发布时间】:2019-11-19 02:38:18
【问题描述】:
我正在尝试从我的服务器获取一个 json 字符串并对其进行解析。一切正常,除了我的 onreadystatechange 仅在我在 .send() 方法之后发出警报时触发。如果没有警报,服务器并不总是收到“GET”请求。我发现解决问题的唯一方法是在 open() 上将 async 设置为 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>
【问题讨论】:
-
很可能是浏览器在脚本触发之前离开了页面。没有minimal reproducible example 就无法分辨
-
尝试在控制台登录给你的 responseText,可能是格式错误的 JSON (
console.log(xhttp.responseText);)。 -
我在调用函数的地方添加了 html。 json也很好。如果我进入 onreadystatechange 函数按预期工作!
标签: javascript asynchronous xmlhttprequest