我正在尝试用javascript替换HTML文件中JSON文件中的数据

时间:2018-12-02 04:26:48

标签: javascript html json

JSON {“好处”:[         {             “ title”:“免费”,             “ description”:“会员免费送货”         },         {             “ title”:“交货”,             “ description”:“您的旅程将始终在交付中”         },         {             “ title”:“新闻”,             “描述”:“双周简讯”         }     ]     }

JAVASCRIPT

var benefitsVar = document.getElementById("memberBenefits");
or (var l=0; l < dataPull.benefits.length; l++){

benefitsVar[l].getElementsByTagName('h4')[0].innerHTML = 
dataPull.benefits[l].title;
benefitsVar[l].getElementsByTagName('p')[0].innerHTML = 
dataPull.benefits[l].description;

};

HTML

<section id="memberBenefits">

<ul>
  <li > <h4 class="benefits">Lorem Ipsum</h4></li>
 <li> <p class="benefits">Lorem ipsum dolor sit amet, consectetur 
adipiscing elit, sed do eiusmod tempor </p></li>
</ul>
<ul>
 <li> <h4 class="benefits">Lorem Ipsum</h4></li>
<li><p class="benefits">Lorem ipsum dolor sit amet, consectetur 
adipiscing elit, sed do eiusmod tempor </p></li>
</ul>

<ul>
    <li> <h4 class="benefits">Lorem Ipsum</h4></li>
    <li ><p class="benefits">Lorem ipsum dolor sit amet, consectetur 
adipiscing elit, sed do eiusmod tempor </p></li>

</ul></section>

1 个答案:

答案 0 :(得分:1)

使用ajax的方法如下:

注意:我不明白为什么你不想使用jquery。如果使用jquery不会造成伤害。将jquery用于ajax事物,将javascript用于其他事物:

$.ajax({
    url: 'http://localhost/data.json',
    crossDomain:true,
    dataType: 'json',             
    success: function(data){
    var newData = '';
    var i;
    for(i=0; i<benefits.length; i++){
     newData +='<ul>'+
    '<li > <h4 class="benefits">'+benefits[i].title+'</h4></li>'+
    '<li ><p class="benefits">'+benefits[i].description+' </p></li>'+
    '</ul>';

    }
$('#memberBenefits').html(newData);
    },
    error: function(){
        console.log('Could not get Data from the file');
    }
});   

您的html:

<section id="memberBenefits">


</section>