2015-10-19 40 views
0

我在做一個API調用此代碼:通過JQuery AJAX請求收到我的數據有什麼問題?

$.ajax({ 
    type: "GET", 
    url: "https://example/example.json", 
    beforeSend: function(xhr) { 
     xhr.setRequestHeader("apikey", "user") 
    }, 
    success: function(data){ 
     alert(data.folder.item); 
    } 
}) 

不返回任何內容,除了在控制檯中的錯誤說:

"Uncaught TypeError: Cannot read property 'item' of undefined"

的JSON數據是這樣的,當我使用在瀏覽器中的網址:

{ 
    "folder": { 
     "item": 123123, 
     "item 2": false, 
     "item 3": "content", 
     "item 4": [ 
      { 
       "subitem": "content" 
      }, 
      { 
       "subitem": "content2" 
      } 
     ] 
    } 
} 

我期待在警告框中顯示「123123」,但不是。那麼我做錯了什麼?

+3

登錄'data'到控制檯,看看它實際上包含。 – CBroe

+0

同樣看看你的開發人員工具的Net標籤中的響應,並確保你獲得了JSON(使用正確的內容類型)。 – Quentin

+0

謝謝CBroe,我對代碼並不是很有經驗,所以它沒有拿到我的賬戶上。這讓我看到整個身份驗證沒有正確完成。該API不提供Javascript的例子,所以我創建的整個呼叫只是不工作。感謝提示,當我走入這樣的問題時,我會牢記它。 – Joris508

回答

1

如果它獲得它的JSON字符串將需要解析。試試這個:

$.ajax({ 
    type: "GET", 
    url: "https://example/example.json", 
    beforeSend: function(xhr) { 
     xhr.setRequestHeader("apikey", "user") 
    }, 
    success: function(data){ 
     var parsed = JSON.parse(data); 
     alert(parsed.folder.item); 
    } 
}); 

或者強迫jQuery來分析它給你:

$.ajax({ 
    type: "GET", 
    url: "https://example/example.json", 
    dataType: 'json', 
    beforeSend: function(xhr) { 
     xhr.setRequestHeader("apikey", "user") 
    }, 
    success: function(data){ 
     alert(data.folder.item); 
    } 
}); 
+0

我以爲jQuery會自動執行此操作嗎? – Mathletics

+2

@Mathletics - 只有當服務器輸出正確的內容類型(或者用'dataType'覆蓋它)時,它纔會**但**。 – Quentin

+1

如果你添加'dataType:「json」'到'ajax'參數 – Igor