javascript - 尝试使用 JS 在 HTML 中显示 Json 响应

标签 javascript html

我正在尝试在网页上显示 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/

相关文章:

html - 如何使用内联 CSS 更改处于事件状态的按钮的颜色?

javascript - 将文本转换为链接的 Tampermonkey 脚本

javascript - AngularJS:如何在选择另一个跨度时取消选择一个跨度

javascript - 动态选项卡的奇怪行为

javascript - 使用 Canvas API 时有哪些典型的设计模式?

javascript - 取消按钮 HTML jQuery

html - 非正常的 HTML 流程

javascript - ASP.NET MVC 如何在javascript中获取所选对象的某些字段?

javascript - 无法加载资源 : Uncaught ReferenceError: InfoBox is not defined at mainMap

jquery - CSS :not():hover selector