2017-02-08 92 views
0

這是我第一次嘗試向API發出跨域Ajax請求。我正在使用jQuery進行調用,並試圖將返回的某些項目放到頁面上。jQuery Ajax請求(CORS)返回undefined

這裏的要求:

$.ajax({ 
    type: 'POST', 
    url: 'http://magicseaweed.com/api/APIKEY/forecast/?spot_id=665', 
    contentType: "text/plain", 
    dataType: "json", 
    xhrFields: { 
      withCredentials: false 
    }, 
    success: function(data) { 
      timestamp = data.localTimestamp; 
      alert(timestamp); 
    }, 
    error: function() { 
      alert("aw crap"); 
    } 
}); 

這裏的響應:

[{ 
    timestamp: 1366902000, 
    localTimestamp: 1366902000, 
    issueTimestamp: 1366848000, 
    fadedRating: 0, 
    solidRating: 0, 
    swell: { 
     minBreakingHeight: 1, 
     absMinBreakingHeight: 1.06, 
     maxBreakingHeight: 2, 
     absMaxBreakingHeight: 1.66, 
     unit: "ft", 
     components: { 
      combined: { 
      height: 1.1, 
      period: 14, 
      direction: 93.25, 
      compassDirection: "W" 
     }, 
     primary: { 
      height: 1, 
      period: 7, 
      direction: 83.37, 
      compassDirection: "W" 
     }, 
     secondary: { 
      height: 0.4, 
      period: 9, 
      direction: 92.32, 
      compassDirection: "W" 
     }, 
     tertiary: { 
      height: 0.3, 
      period: 13, 
      direction: 94.47, 
      compassDirection: "W" 
     } 
    } 
}] 

目前,我只是想獲得時間戳字符串中的一個警告框來顯示。

alert(timestamp);由於未定義而返回。我的錯誤在哪裏?

+0

數組什麼警報'輸出(數據)',甚至更好'的console.log(JSON.stringify (data))' - nvm,剛剛看到你的數據結構。 @Abdennour TOUMI答案正確 – JorgeObregon

+0

看起來響應是一個數組。你有沒有試過'data [0] .localTimestamp' –

回答

3
 timestamp = data[0].localTimestamp; 

 timestamp = data.localTimestamp; 

因爲響應是一個項目[{...}]