【问题标题】:creating html div from json using javascript使用javascript从json创建html div
【发布时间】:2019-11-28 16:35:45
【问题描述】:

我想在 div 中创建一个滑动图片库。为了获取图像和描述,我在 api 上发出 get 请求。返回的 json 符合预期,在此之前,代码可以正常工作。

我在 W3Ccourses https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_slideshow_auto 上找到了这个滑动画廊,我想将它与我的数据一起使用。

我收到以下 2 个错误:

  • 无法获取未定义或空引用的属性“样式”这是代码

  • 'require' 未定义

我尝试过使用 require.js,但没有成功。我尝试使用 document.createElement 然后 .appendChild 创建我的 div,但它没有用。我认为问题不在于创建 html 元素。谢谢回复

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
* {box-sizing: border-box;}
body {font-family: Verdana, sans-serif;}
.mySlides {display: none;}
img {vertical-align: middle;}

/* Slideshow container */
.slideshow-container {
  max-width: 1000px;
  position: relative;
  margin: auto;
}

/* Caption text */
.text {
  color: #f2f2f2;
  font-size: 15px;
  padding: 8px 12px;
  position: absolute;
  bottom: 8px;
  width: 100%;
  text-align: center;
}

/* Number text (1/3 etc) */
.numbertext {
  color: #f2f2f2;
  font-size: 12px;
  padding: 8px 12px;
  position: absolute;
  top: 0;
}

/* The dots/bullets/indicators */
.dot {
  height: 15px;
  width: 15px;
  margin: 0 2px;
  background-color: #bbb;
  border-radius: 50%;
  display: inline-block;
  transition: background-color 0.6s ease;
}

.active {
  background-color: #717171;
}

/* Fading animation */
.fade {
  -webkit-animation-name: fade;
  -webkit-animation-duration: 1.5s;
  animation-name: fade;
  animation-duration: 1.5s;
}

@-webkit-keyframes fade {
  from {opacity: .4}
  to {opacity: 1}
}

@keyframes fade {
  from {opacity: .4}
  to {opacity: 1}
}

/* On smaller screens, decrease text size */
@media only screen and (max-width: 300px) {
  .text {font-size: 11px}
}
</style>
</head>
<!-- ####################################################### -->
<body>
<div class="slideshow-container">
<!-- ### want to get this kind of div , but with my data ###
<div class="mySlides fade">
  <div class="numbertext">1 / 3</div>
  <img src="img_nature_wide.jpg" style="width:100%">
  <div class="text">Caption Text</div>
</div>  -->

<script type="text/javascript">

url  = 'http://www.myUrl.com';

var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
var httpReq = new XMLHttpRequest();
httpReq.open("GET" , url , false);
httpReq.send(null);
var jsonObj = JSON.parse(httpReq.responseText);
var description = jsonObj[i].description

for ( i = 0 ; i < 9 ; i++) {
document.writeln('<div class=\"mySlides fade\">');
document.writeln('<div class = \"numbertext\">' + i + '/9</div>');
document.writeln('<a href = \"https://www.that-product.com\"><img src=\"' + jsonObj[i].url_image + '\" style="width :100%"></a>');
document.writeln('<div class=\"text\">' + description + '</div>');
}
</script>
</div>

<div style="text-align:center">
  <span class="dot"></span>
  <span class="dot"></span>
  <span class="dot"></span>
  <span class="dot"></span>
  <span class="dot"></span>
  <span class="dot"></span>
  <span class="dot"></span>
  <span class="dot"></span>
  <span class="dot"></span>
</div>

<script>
var slideIndex = 0;
showSlides();

function showSlides() {
  var i;
  var slides = document.getElementsByClassName("mySlides");
  var dots = document.getElementsByClassName("dot");
  for (i = 0; i < slides.length; i++) {
    slides[i].style.display = "none";
  }
  slideIndex++;
  if (slideIndex > slides.length) {slideIndex = 1}
  for (i = 0; i < dots.length; i++) {
    dots[i].className = dots[i].className.replace(" active", "");
  }
  slides[slideIndex-1].style.display = "block";
  dots[slideIndex-1].className += " active";
  setTimeout(showSlides, 2000); // Change image every 2 seconds
}
</script>
</body>
</html>

【问题讨论】:

  • 对于require is not defined 错误,您似乎正在尝试在浏览器中使用Node.js require function,但这是行不通的。看到这个答案:stackoverflow.com/a/9901097/8135076
  • 对于'style' of undefined 错误,您的slides 变量未定义,因为将&lt;div&gt;s 附加到mySlides 类的函数由于require is not defined 错误而失败。跨度>
  • 我在您的代码中看到了一堆问题:1. 您没有验证 ajax 调用的响应,2. 每个 Ajax 调用真的有 9 个条目吗? 3. 为什么要屏蔽“insight the document-writeln 字符串”? 4. showSlides 函数将被调用递归作为回调insight the setTimeout

标签: javascript html require


【解决方案1】:

我检查了你的代码,我注意到三件事,

  • 你不需要这行 var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest; 你不需要在这里因为 XMLHttpRequest 是 windows 对象的一部分。

  • 您对 xmlhttprequest 方法的使用是错误的,请参阅下面的正确实现。

var url  = 'http://www.myUrl.com';
var httpReq = new XMLHttpRequest();

httpReq.open("GET" , url);
httpReq.send(null);

var jsonObj, description;
httpReq.onload = function() {
  if (httpReq.status == 200) { // analyze HTTP status of the response
    var jsonObj = JSON.parse(httpReq.responseText);
    var description = jsonObj[i].description // e.g. 404: Not Found
    for ( i = 0 ; i < 9 ; i++) {
      document.writeln('<div class=\"mySlides fade\">');
      document.writeln('<div class = \"numbertext\">' + i + '/9</div>');
      document.writeln('<a href = \"https://www.that-product.com\"><img src=\"' + jsonObj[i].url_image + '\" style="width :100%"></a>');
      document.writeln('<div class=\"text\">' + description + '</div>');
    }
    var slideIndex = 0;
    showSlides();
  } else { // show the result
    alert(`Error: httpReq.status`); // responseText is the server
  }
};
  • 如果您不是从与http://www.myUrl.com 相同的来源运行此程序,您将收到 CORS 错误

希望这会有所帮助。

【讨论】:

    【解决方案2】:

    您可以使用 ajax 请求来检索您的 json 数据,然后在附加 mySlides div 时循环每个对象

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"> </script>
    <script>
    $(document).ready(function(){
        $.getJSON("https://jsonplaceholder.typicode.com/todos/1", function(result){
          $.each(result, function(i, field){
            $("div.slideshow-container").append(`<div class="mySlides fade"><div class="numbertext">1 / 3</div><img src="${field.url}" style="width:100%"><div class="text">${field.caption}</div></div>`);
          });
        });
     showSlides();
    });
    
    </script>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-27
      • 2011-10-02
      • 1970-01-01
      • 2012-12-06
      • 2013-03-19
      • 2014-05-05
      相关资源
      最近更新 更多