2013-03-02 49 views
0

好吧,我知道這聽起來很愚蠢,因爲下面的代碼應該是工作的Javascript JSON.parse SUB JSON

document.getElementById('petimg').src = petJSON[0].picture[0].large; 

但它總是崩潰網站

以下是完整的代碼

xmlhttp=new XMLHttpRequest(); 
xmlhttp.open("GET","http://service.ipetfindr.com/iOS/?uri=fetchpet/13373A" + n[1],false); 
xmlhttp.send(); 

var petJSON = JSON.parse(xmlhttp.responseText); 

alert(petJSON[0].picture.large); 

document.getElementById('petimg').src = petJSON[0].picture.[0].large; 
document.getElementById("petname").innerHTML = petJSON[0].petname; 
document.getElementById("breed").innerHTML = petJSON[0].breed; 
document.getElementById("petid").innerHTML = petJSON[0].ipetfindrtagid; 

我有一個問題JSON的部分是以下

"picture":[{"large":"http:\/\/www.ipetfindr.com\/petuploads\/7b2b07363b271703782d0b7d5362f8f4.JPG","small":"http:\/\/www.ipetfindr.com\/petuploads\/7b2b07363b271703782d0b7d5362f8f4-x-h80.JPG"}] 

編輯FIX 修復這個錯誤的方法很簡單

xmlhttp=new XMLHttpRequest(); 
xmlhttp.open("GET","http://service.ipetfindr.com/iOS/?uri=fetchpet/13373A" + n[1],false); 
xmlhttp.send(); 

var petJSON = JSON.parse(xmlhttp.responseText); 
var petpicture = petJSON[0].picture[0]; 
alert(petpicture.large); //THIS allows me or anyone to call the large image in the sub array 

document.getElementById('petimg').src = petJSON[0].picture.[0].large; 
document.getElementById("petname").innerHTML = petJSON[0].petname; 
document.getElementById("breed").innerHTML = petJSON[0].breed; 
document.getElementById("petid").innerHTML = petJSON[0].ipetfindrtagid; 
+0

向我們展示您遇到的異常(來自錯誤控制檯) – Bergi 2013-03-02 16:05:08

+0

我在控制檯中沒有看到任何錯誤,因爲它的電話應用程序崩潰 – RussellHarrower 2013-03-02 16:06:21

+0

難道是您的XHR掛起?你正在使用阻止模式,所以如果它需要一段時間來接收它可能會導致網站/應用程序崩潰 – SReject 2013-03-02 16:08:45

回答

0

petJSON[0].picture.[0].large是一個語法錯誤。刪除[之前的點,只能使用點或括號符號到access properties

+0

這樣做的工作如此惡劣勾選此答案 – RussellHarrower 2013-03-02 16:56:11