简体   繁体   English

如何从链接中获取 JSON 数据并将其解析为 HTML

[英]How do I get JSON data from a link and parse it into HTML

Here is my pen and there I have to make a request to this link , retrieve the data, put it into JavaScript and show on a page, but my request yields an empty response.这是我的,我必须向此链接发出请求,检索数据,将其放入 JavaScript 并显示在页面上,但我的请求产生了空响应。 What might be wrong and how can I do it better?可能有什么问题,我怎样才能做得更好?

    // Get the modal element

var modal = document.getElementById('simpleModal');

var modalBtn = document.getElementById('modalBtn');

var closeBtn = document.getElementById('closeBtn');

modalBtn.addEventListener('click', openModal);

var requestResultData;

// Listen for a close click
closeBtn.addEventListener('click', closeModal);

//Outside click
window.addEventListener('click', clickOutside);

// Function 

function openModal() {
  modal.style.display = 'block';
  dataRequest();
}

function dataRequest () {
  var xhr = new XMLHttpRequest();

  xhr.onreadystatechange = function() {
    if (xhr.readyState === 4){
         console.log(xhr);
      }
  };
  xhr.open('GET','http://www.omdbapi.com/?i=tt5687270&apikey=480344f1');
  xhr.send();
}

// function to close modal

function closeModal() {
  modal.style.display = 'none';
}

// Function for an outside click


function clickOutside(e) {

  if(e.target == modal) {
      modal.style.display = 'none';
  }

}

You can use the fetch api您可以使用 fetch api

fetch("https://yourwebsite.com/data.json")
.then(res=>res.json())
.then(res=>{
    //do something with the data here
    console.log(res);
});

More about the fetch api here更多关于 fetch api在这里

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

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