我正在尝试在网页上显示 json,并且使用以下代码,但它不起作用,谁可以帮助我理解我做错了什么?
<button type="submit" onclick="javascript:send()">call</button>
<div id="div"></div>
<script type="text/javascript" language="javascript">
function send()
{
var xmlhttp = new XMLHttpRequest();
//xmlhttp.onreadystatechange = callbackFunction(xmlhttp);
xmlhttp.open("GET", "http://stam/1.1/json/url=https://www.google.co.il");
xmlhttp.setRequestHeader("Content-type", "application/json");
xmlhttp.send();
xmlhttp.responseType = 'json';
xmlhttp.setRequestHeader("Content-Type", "application/json");
//xmlhttp.onreadystatechange = callbackFunction(xmlhttp);
var requestDoneAndOK = false;
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4) {
if (xmlhttp.status === 200) {
//requestDoneAndOK = true;
var jsonResponse = JSON.parse(xmlhttp.responseText);
document.getElementById("div").innerHTML = xmlhttp.statusText + ":" + xmlhttp.status + "<BR><textarea rows='100' cols='100'>" + jsonResponse + "</textarea>";
}
}
};
}
</script>
最佳答案
您的网址不正确。此外,您还应该删除代码中提到的注释掉的行以使其正常工作。
您可以使用此虚拟网址来检查它是否正常工作: https://reqres.in/api/users?page=2
function send()
{
var xmlhttp = new XMLHttpRequest();
//xmlhttp.onreadystatechange = callbackFunction(xmlhttp);
xmlhttp.open("GET", "http://stam/1.1/json/url=https://www.google.co.il");
xmlhttp.setRequestHeader("Content-type", "application/json");
xmlhttp.send();
// Remove the below commented lines and change the url
// xmlhttp.responseType = 'json';
// xmlhttp.setRequestHeader("Content-Type", "application/json");
// xmlhttp.onreadystatechange = callbackFunction(xmlhttp);
var requestDoneAndOK = false;
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === 4) {
if (xmlhttp.status === 200) {
//requestDoneAndOK = true;
var jsonResponse = JSON.parse(xmlhttp.responseText);
document.getElementById("div").innerHTML = xmlhttp.statusText + ":" + xmlhttp.status + "<BR><textarea rows='100' cols='100'>" + jsonResponse + "</textarea>";
}
}
};
}
关于javascript - 尝试使用 JS 在 HTML 中显示 Json 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44738792/