微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用json数据制作卡片滑块

如何解决如何使用json数据制作卡片滑块

我正在尝试使用这样的 json 数据制作卡片滑块:http://femkreations.com/projects/ajax/ajax-carousel/index.php 而我想使用来自此网址的 json 数据:https://api.thecatapi.com/v1/breeds显示 5 张卡片,其中包含名称、描述和图片来自猫。我已经用 XMLHttpRequest 加载了 json 数据,但我真的不知道我现在需要做什么。我是这些方面的初学者,希望有人能帮助我。

解决方法

首先要根据自己的JSON数据定义要使用的模板 为了简化起见,假设您的 JSON 看起来像这样

{
  cats: [

       {
        name: "rico",power_level: "500",bio: "nice dude"
       },{
        name: "johnnyboi",power_level: "1200",bio: "bad guy"  
       },{
        name: "earl",power_level: "over9000",bio: "stronk guy"
       }
     ]
}

这家伙用这样的 HTML 代码定义模板(介于 HTML 代码之间)。请注意,您必须工作或复制 CSS 类扬声器。

<script id="speakerstpl" type="text/template">
{{#speakers}}
    <div class="speaker">
        <img src="images/{{shortname}}_tn.jpg" alt="Photo of {{name}}" />
        <h3>{{name}}</h3>
        <h4>{{reknown}}</h4>
        <p>{{bio}}</p>
    </div>
{{/speakers}}
</script>

因此,让我们按照您想要的方式为我上面写的 JSON 调整模板:

<script id="speakerstpl" type="text/template">
{{#cats}}
    <div class="speaker">            
        <h3>{{name}}</h3>
        <h4>{{power_level}}</h4>
        <p>{{bio}}</p>
    </div>
{{/cats}}
</script>

现在,在我们使用函数背后的魔法之前,请注意此页面使用了以下外部库(不要忘记将它们添加到您的文档中):

<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery.cycle/2.9999.8/jquery.cycle.all.min.js" type="text/javascript"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/mustache.js/0.7.0/mustache.min.js" type="text/javascript"></script>

让我们打电话:

var data = {
  cats: [

       {
        name: "rico",bio: "stronk guy"
       }
     ]
}

var template = $('#speakerstpl').html();
var html = Mustache.to_html(template,data);
$('#carousel').html(html); //this element is a div inside another div (wrapper)
//final step for the rotation/cycle
$('#carousel').cycle({
        fx: 'fade',pause: 1,next: '#next_btn',prev: '#prev_btn',speed: 500,timeout: 10000
    });

编辑:这里是来自 https://developpaper.com/xmlhttprequest-for-asynchronous-requests/ 的简单代码,以便顺便获取您的数据:

var data = {cats: []};
var xhr = new XMLHttpRequest(),method = "GET",url = "https://api.thecatapi.com/v1/breeds";

xhr.open(method,url,true);
xhr.responseType = "json";
xhr.onreadystatechange = function () {

if(xhr.readyState === xhr.DONE) {
  if (xhr. status === 200) {// successful request
    console.log(xhr.response);
    //capture this response using your data variable
    data.cats = xhr.response;
     
  } else {// request failed
      console.log(xhr.response);
  }    
 }
};
xhr.ontimeout = function(event){
console.log('request timeout!');
}
xhr.setRequestHeader('Content-Type','application/json');
xhr.send();

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。