2013-11-01 24 views
3

我試圖使用strava v3 api來獲取數據。我對JS很新。我複製了示例XMLHttpRequest代碼,但我得到的只是返回的空字符串。如果我去瀏覽器中的鏈接manually,它工作正常。我也試過這個使用jquery,我得到了同樣的東西。Strava v3 api JS GET數據

function reqListener() { 
      console.log(this.responseText); 
     }; 

     var oReq = new XMLHttpRequest(); 
     oReq.onload = reqListener; 
     oReq.open("get", "https://www.strava.com/api/v3/athlete/activities?per_page=1&access_token=83ebeabdec09f6670863766f792ead24d61fe3f9", true); 
     oReq.send(); 

任何想法?

編輯:用jquery。還不行的

<html> 
    <head> 
     <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> 
    </head> 
    <body> 
     <span id="hello">hello</span> 
     <script> 
      $(document).ready(function() { 
       $.getJSON("https://www.strava.com/api/v3/athlete/activities?per_page=1&access_token=83ebeabdec09f6670863766f792ead24d61fe3f9&callback=?", function(data) { 
        $('#hello').html(data); 
       }); 
      }); 
     </script> 
    </body> 
</html> 

回答

0

你與標記這一點,所以use jQuery

$.get("https://www.strava.com/api/v3/athlete/activities?per_page=1&access_token=83ebeabdec09f6670863766f792ead24d61fe3f9", function (results) { 
    // use returned results 
}); 
1

從他們的文檔:

JSON-P callbacks

Specify the ?callback=function_name parameter to request a JSONP compatible response. This is compatible with JavaScript libraries such as jQuery.

所以我建議你使用jQuery to trigger a JSONP request來他們:

$.getJSON("https://www.strava.com/api/v3/athlete/activities?per_page=1&access_token=yourAccessToken&callback=?", function (data) { 
    // your code in here 
}); 


編輯

作爲每下面的評論:在這種形式(沒有替換的?的)信號將jQuery的callback=?,這是一個JSONP請求。 jQuery本身會將?更改爲回調的某個函數名稱,該函數基本上執行您傳遞給$.getJSON()的函數。

+0

謝謝。我仍然無法讓它工作,雖然...編輯原始帖子。 – stuppie

+0

@stuppie目前爲我返回一個「NetworkError:400 Bad Request」錯誤。返回的JSONP說了一些關於「不允許」的內容,所以我想現在你不能使用JSONP,因此直接在客戶端使用API​​。不過,您可能能夠檢索服務器上的數據。 – Sirko

+0

我該怎麼做?如果我只是在瀏覽器中訪問該網址,它就會起作用。有沒有辦法只是抓住文本? – stuppie