2014-09-19 62 views
0

我想導入一個json文件,當我打電話$(document).ready(function(){}。我的html表單需要在json文件中定義的屬性。 我該怎麼做?如何導入JavaScript中的json文件?

+1

試試這個'$ .getJSON( '路徑',函數(數據){執行console.log(數據);})' – Girish 2014-09-19 11:42:17

回答

1

一個例子如何做到這一點可能是:

<script type="text/javascript"> 
    $(function(){ 
     $.getJSON('names.json',function(data){ 
      console.log('success'); 
      $.each(data.employees,function(i,emp){ 
       $('ul').append('<li>'+emp.firstName+' '+emp.lastName+'</li>'); 
      }); 
     }).error(function(){ 
      console.log('error'); 
     }); 
    }); 
</script> 
1

嘗試這樣的:

$.getJSON("path to json file", function(data) { 
     var item = []; 
     $.each(data, function(key, val) { 
     item.push("<li id='" + key + "'>" + val + "</li>"); 
     }); 

     $("<ul/>", { 
     "class": "myclass", 
     html: item.join("") 
     }).appendTo("body"); 
    });