2016-04-18 24 views
-2

我有JSON文件result.json尋找如下:如何打開JSON文件和存取權限及其對象

{ 
"employees":[ 
    {"firstName":"John","lastName":"Doe" }, 
    {"firstName":"Anna","lastName":"Smith" }, 
    {"firstName":"Peter","lastName":"Jones" }] 
} 

在我的HTML文件,我試圖使用jQuery訪問從對象之一json文件,即其中一個人,並顯示一些對象數據。

<!DOCTYPE html> 
<html> 
<body> 
<head> 
    <script type = "text/javascript" src = "http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> 
</head> 

<p id="demo"></p> 

<script> 
    var obj; 
    $.getJSON("http://insyn.local:666/result.json", function(json){ 
     obj = json; 
    }); 
    document.getElementById("demo").innerHTML = 
    obj.employees[1].firstName + " " + obj.employees[1].lastName; 
</script> 

</body> 
</html> 

但這只是給我的錯誤「遺漏的類型錯誤:無法讀取的未定義的屬性‘員工’」。我在這裏錯過了什麼?

+1

由於JS的異步性,你需要把'innerHTML'聲明在'getJSON'調用回調函數。否則,innerHTML將在結果返回之前運行。 – helllomatt

+1

'$ .getJSON'是一個異步調用,當您嘗試將其插入DOM時可能還未完成 – Craicerjack

回答

0

嘗試做回調裏面你的HTML操作:

<!DOCTYPE html> 
<html> 
<body> 
<head> 
    <script type = "text/javascript" src = "http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> 
</head> 

<p id="demo"></p> 

<script> 
    var obj; 
    $.getJSON("http://insyn.local:666/result.json", function(json){ 
     obj = json; 
     document.getElementById("demo").innerHTML = 
     obj.employees[1].firstName + " " + obj.employees[1].lastName; 
    }); 

</script> 

</body> 
</html> 
相關問題