简体   繁体   English

如何从URL加载JSON并通过在HTML页面上使用纯JavaScript进行显示?

[英]How to load JSON from URL and display by using plain javascript on HTML page?

I'm trying to get JSON data from the specific URL and display it on the HTML page to check whether it works or not. 我正在尝试从特定的URL获取JSON数据,并将其显示在HTML页面上,以检查其是否有效。 I have no idea about what is wrong and I should fix on my code. 我不知道出什么问题了,应该修复我的代码。

<script>
        var jsonDoc="";
        function loadJSON(url){
            //alert(url);
            var request = new XMLHttpRequest();

            request.open('GET', url, false);
            request.responseType = 'json';
            request.onreadystatechange = function(){
                if(request.readyState == 4 && request.status == 200){
                    jsonDoc = JSON.parse(request.responseText);
                }else{
                    jsonDoc = null;
                }

                request.send();

            };
        }
        document.getElementById('content').innerHTML = jsonDoc;
</script>

<body>
    <h1>Enter URL for Highest-grossing films List JSON File</h1>
    <form>
        <input type="text" id="url" value=""><br>
        <input type="button" name="submit" value="Submit Query" onclick="loadJSON(document.getElementById('url').value)">
    </form>

    <div id="content"></div>
</body>

There are a number of errors preventing your code from doing what you want it to do. 有很多错误阻止您的代码执行您想要的操作。

  1. You are trying to access the element that has the content id before the element is loaded on the page. 您试图在页面上加载元素之前访问具有content ID的元素。 Think of it like this. 这样想吧。 Your script and body elements are organized in such a way that your script will load and execute first before the body element and its children are loaded. 您的scriptbody元素的组织方式使得您的script将在body元素及其子元素加载之前首先加载并执行。

    The culprit is this line: document.getElementById('content').innerHTML = jsonDoc . 罪魁祸首是这一行: document.getElementById('content').innerHTML = jsonDoc

    It belongs in the onreadystatechange function because you only want to update content when you have received the data from the API. 它属于onreadystatechange函数,因为您仅在从API接收数据后才想更新content

    If you move that line to the onreadystatechange function, you now have access to the data you retrieved from the API and do not need the jsonDoc global variable. 如果将该行移至onreadystatechange函数,则现在可以访问从API检索的数据,并且不需要jsonDoc全局变量。

  2. The request.responseType = 'json' code raises this descriptive error. request.responseType = 'json'代码引发此描述性错误。

    InvalidAccessError: synchronous XMLHttpRequests do not support timeout and responseType.

    Delete that line of code because it is attempting an operation that is not allowed. 删除该行代码,因为它正在尝试不允许的操作。

  3. You are never sending a request because request.send() is inside the code that handles the API's response. 您永远不会发送请求,因为request.send()位于处理API响应的代码内。 It should be outside that function. 它应该在该功能之外。

  4. In the onreadystatechange function, you will also want to JSON.stringify the data after using JSON.parse to make it into the string you want to display. onreadystatechange函数中,在使用JSON.parse将数据放入要显示的字符串后,您还需要对数据进行JSON.stringify

After fixing all of that, your JavaScript should look similar to this. 修复所有问题后,您的JavaScript应该看起来与此类似。

<script>
  function loadJSON(url) {
    let request = new XMLHttpRequest();

    request.open('GET', url, false);
    request.onreadystatechange = function() {
      if (request.readyState == 4 && request.status == 200) {
        const data = JSON.parse(request.responseText);
        document.getElementById('content').innerHTML = JSON.stringify(data);
      }
    };
    request.send();
  }
</script>

A more modern JavaScript practice is to use the fetch API. 更现代的JavaScript做法是使用fetch API。 It makes fetching data from APIs a lot easier. 它使从API提取数据变得更加容易。 Here is the equivalent of the code above, using the fetch API. 这与使用fetch API的上述代码等效。

<script>
  function loadJSON(url) {
    fetch(url)
      .then(function(res) { return res.json(); })
      .then(function(data) {
         document.getElementById('content').innerHTML = JSON.stringify(data);
      });
  }
</script>

You can read more about using the Fetch API on MDN. 您可以阅读有关在MDN上使用Fetch API的更多信息。

Add it to the DOM after response is received. 收到响应后将其添加到DOM。

request.onreadystatechange = function() {
  // here
};

Also move request.send(); 还移动request.send(); outside of request.onreadystatechange callback: request.onreadystatechange回调之外:

    var jsonDoc="";
    function loadJSON(url){
        //alert(url);
        var request = new XMLHttpRequest();

        request.open('GET', url, false);
        request.responseType = 'json';
        request.onreadystatechange = function(){
            if(request.readyState == 4 && request.status == 200){
                jsonDoc = JSON.parse(request.responseText);
                document.getElementById('content').innerHTML = jsonDoc;
            }else{
                jsonDoc = null;
            }
        };
        request.send();
    }

I may be off base here, but the main thing I thought was wrong in your approach was that the input text field did not have a 'name' field. 我在这里可能不满意,但是我认为您的方法最主要的错误是输入文本字段没有“名称”字段。 I made some changes in your code so that I could track down a way to get the value of that name field out to look at its value. 我对您的代码进行了一些更改,以便找到一种方法来获取该名称字段的值,以查看其值。 This may not be what you wanted, but it gives a way to find your parameters and you can then do with them as you wish. 这可能不是您想要的,但是它提供了一种找到参数的方法,然后您可以根据需要使用它们。 Here is the modified code with a couple of simple javascript functions to assist: 这是经过修改的代码,其中包含几个简单的javascript函数以提供帮助:

<html>
<head>
<script>
function getURLParameters(paramName)
{
    var sURL = window.document.URL.toString();
    alert('sURL = ' + sURL);
    if (sURL.indexOf("?") > 0)
    {
        var arrParams = sURL.split("?");
        var arrURLParams = arrParams[1].split("&");
        var arrParamNames = new Array(arrURLParams.length);
        var arrParamValues = new Array(arrURLParams.length);

        var i = 0;
        for (i = 0; i<arrURLParams.length; i++)
        {
            var sParam =  arrURLParams[i].split("=");
            arrParamNames[i] = sParam[0];
            if (sParam[1] != "")
                arrParamValues[i] = unescape(sParam[1]);
            else
                arrParamValues[i] = "No Value";
        }

        for (i=0; i<arrURLParams.length; i++)
        {
            if (arrParamNames[i] == paramName)
            {
                alert("Parameter:" + arrParamValues[i]);
                return arrParamValues[i];
            }
        }
        return "No Parameters Found";
    }
}
 function printDiv(divName) {
     alert('In printDiv with divName '+divName);
     var printContents = document.getElementById(divName).innerHTML;
     var originalContents = document.body.innerHTML;

     var replyStr = "Post parameters for 'dest':\r\n" + getURLParameters('dest'); // "1234";
     alert(replyStr);
     document.write(replyStr);
//     document.body.innerHTML = replyStr;
}
</script>
</head>
<body>
    <h1>Enter URL </h1>
    <form >
        <input type="text"  name="dest" value=""/><br/>
        <br />
        <input type="submit" name="submit" value="Submit Query" onClick="return(printDiv('printableArea'))"/>
    </form>

    <div id="content"></div>
    <div id="printableArea">
      <h1>Print me</h1>
</div>

</body>
</html>

I was going to put the response back into the printableAres innerHTML, but got it to write out and stopped there. 我打算将响应放回printableAres innerHTML中,但要写出来并停在那里。 Main changes were to add a name 'dest' to the textfield that received the URL, and process the form data using getURLParams for the field value for 'dest'. 主要更改是在接收URL的文本字段中添加名称“ dest”,并使用getURLParams作为“ dest”的字段值来处理表单数据。 You can probably work out what you wanted to do from here. 您可能可以从这里算出您想做什么。 Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM