【问题标题】:Read JSON and implement it in HTML读取 JSON 并在 HTML 中实现
【发布时间】:2019-06-17 05:07:00
【问题描述】:

首先,对不起我的英语不好,不是最好的;)

所以我是使用 JavaScript、Ajax 和 jQuery 的新手。从小我就对编码很感兴趣。我的一个朋友想要更新我不久前为他们制作的他们的网站。他们有一个小型播客/广播电台。

我要做的是在他们发布在 MixCloud 上的播客和他们的网站之间建立一个自动链接。我遵循了一些教程,并在这个网站上扔了表格,但我无法让脚本正常工作并从 MixCloud 使用他们的 API 制作的 JSON 文件中获取信息。

这是我到目前为止所得到的。我不知道我做错了什么,因为我对此非常陌生。我尝试了不同的方法,但这是我得到的最接近的方法。

const Http = new XMLHttpRequest();
const url = 'https://api.mixcloud.com/itmotr-radio/cloudcasts/';
Http.open("GET", url);
Http.send();
Http.onreadystatechange = (e) => {
  console.log(Http.responseText)
}

function append_json(XMLHttpRequest) {

  //Set Up the template
  var s = $("#postTemplate")[0].innerHTML.trim();
  var holder = document.createElement('div');
  holder.innerHTML = s;
  var template = holder.childNodes;

  var episode = document.getElementById('episodes');
  Object.keys(XMLHttpRequest).forEach(function(object) {

    //Clone Template
    var newEpisode = $(template).clone();

    //Populate it
    $(newEpisode).find(".data.name").html(object.episodetitle);

    var img = $(newItem).find(".data.pictures.320wx320h")
    $(img).attr("src", object.coverimg)

    //Append it
    $(".episodes").append(newEpisode);

  });
}

$("document").ready(function() {
  append_json(XMLHttpRequest);
});
.episodes {
  background: white;
  display: grid;
  grid-gap: 10px;
  grid-template-columns: repeat(auto-fit, minmax(320px, 380px));
  grid-auto-rows: 370px;
  grid-auto-flow: dense;
  justify-content: center;
  padding-top: 10px;
}

.episode {
  background: rgb(255, 255, 255);
  border: 1px solid grey;
  text-align: center;
}

.episodetitle {
  font-size: 20px;
  color: red
}

.coverimg {
  width: 320px;
  max-height: 320px
}
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

<div class="episodes">

  <script type="text/template" id="postTemplate">

    <div class="episode">

      <img class="coverimg" src="">
      <p class="episodetitle"></p>

    </div>

  </script>

</div>

由于某种原因,我无法从 JSON 文件中获取数据,并且它不会显示在 HTML 中。我在这篇文章的帮助下构建了这个脚本:Populate grid <div> & <p> with JSON data file

有人可以帮助我并让它与我一起工作吗? 需要读取的 JSON 文件是: https://api.mixcloud.com/itmotr-radio/cloudcasts/

【问题讨论】:

标签: javascript jquery html css json


【解决方案1】:

有一些事情正在发生,所以我将分别解决每个问题,您可以将它们放在一起作为学习:) 不过您的总体结构还可以,到目前为止还不错!

jquery

&lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"&gt;/script&gt;

这是旧版本,请使用

&lt;script src="https://code.jquery.com/jquery-3.3.1.min.js"&gt;&lt;/script&gt;

AJAX

const Http = new XMLHttpRequest();
const url='https://api.mixcloud.com/itmotr-radio/cloudcasts/';
Http.open("GET", url);
Http.send();
Http.onreadystatechange=(e)=>{
console.log(Http.responseText)
}

这一切都在 jquery 中自动处理。阅读AJAX documentation。这是一个很好的学习示例,它非常简单(您可以使用很多默认值)。

$.ajax({
  url:'https://api.mixcloud.com/itmotr-radio/cloudcasts/',
  success:function(data){
    //Do stuff with the data here (as JSON, it should be auto parsed into an object)

    //for example (psuedo code..)
    for(var i = 0; i < data.length;i++){
      //Use the data variable passed in with the success function.
      createNewElement(data[i]) // do something with each object in the array (see below)

    }
})

创建新元素

 var newEpisode = $(template).clone();

 //Populate it
 $(newItem).find(".data.name").html(object.episodetitle);

 var img = $(newItem).find(".data.pictures.320wx320h")
 $(img).attr("src", object.coverimg)

 //Append it
 $(".episodes").append(newEpisode);

由于您已经拥有 jquery,我们可以轻松使用很多功能。我们可以在 jquery 中构建要附加的元素,或者只在包含 HTML 的 javascript 中使用字符串。当您添加动态数据时,制作元素是有意义的。

createNewElement(datum){
 // This function creates a new element each time it is called and appends it to the 
 let $para = $('<p></p>') // make new <p> element
  .addClass('episodetitle') // add the class property and actual classes
  .text(thing.episodetitle) // set the text content of the element
//we have created "<p class='episodetitle'>This is the Title</p>"

//Alernatively we can do it all in one go
let $img = $('<img class="coverimg" src="'+datum.imagesource+'"/>') 

// Now we create the container div for these 2 elements
let $newEpisode = $('<div></div>').addClass('episode')

$newEpisode.append($para) // Add the para into our div
  .append($img) // append the image element into the div


$(".episodes").append($newEpisode); // append the div to the coagulate div

}

【讨论】:

  • 实现了你的一些代码,但它不起作用。我已经在这里发布了我是如何做到的!感谢您到目前为止的帮助:)
【解决方案2】:

@托宾

所以现在我将我的脚本编辑为:

            $.ajax({
            url:'https://api.mixcloud.com/itmotr-radio/cloudcasts/',
            success:function(data){
            //Do stuff with the data here (as JSON, it should be auto parsed into an object)
            var newEpisode = $(template).clone();

            //Populate it
            $(newItem).find(".data.name").html(object.episodetitle);

            var img = $(newItem).find(".data.pictures.320wx320h")
            $(img).attr("src", object.coverimg)
                
            let $para = $('<p></p>').addClass('episodetitle').text(thing.episodetitle)

            let $newEpisode = $('<div></div>').addClass('episode')
            $newEpisode.append($para)
                

     // GETTING A ERROR :28 Uncaught SyntaxError: Identifier '$para' has already been declared. When trying to do the same for the coverimg.

            let $para = $('<p></p>').addClass('coverimg').text(thing.coverimg)
          
            let $newEpisode = $('<div></div>').addClass('coverimg')
            $newEpisode.append($para)

            //Append it
            $(".episodes").append(newEpisode);
            
            }
            })

但是现在 de second $para 给了我一个错误,因为它已经被声明了......

但我在第一个脚本中做了一个更改,将“newItem”更改为“newEpisode”,现在它呈现了我的布局,但没有加载 JSON 文件中的任何信息。它制作了 5 个项目,而应该是 JSON 文件中的 2 个“文件”。这里出了什么问题?

【讨论】:

  • 你能粘贴一个你正在加载的json的例子吗?
  • 这是链接:api.mixcloud.com/itmotr-radio/cloudcasts,无法发布示例,因为评论区太长了!
  • 我已经编辑了我的答案以更清楚地解决您的上述问题...如果有帮助,您能否将其标记为已回答!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-19
  • 2018-07-19
  • 2012-11-30
  • 1970-01-01
  • 1970-01-01
  • 2020-12-03
相关资源
最近更新 更多