Unable to complete the .getJSON request?

余生长醉 提交于 2019-12-11 11:36:03

问题


To start off, this is a cross-domain request I am trying to complete. Here is a link to the Strava API whitepaper that I am using as a reference. Strava Wiki

Please see the code I am using below. If it is not possible to perform the request with jQuery, can you give me an example of another way to do it? (ex. AJAX) I've done my research but I admit that I do not know enough to understand why the request is not working. Do I need to insert an argument that waits for the response before displaying the alert, or is that implied? Thanks in advance!

 <html lang="en">
 <head>
   <meta charset="utf-8">
   <title>jQuery demo</title>
 </head>
 <body>
   <a href="http://jquery.com/">jQuery</a>
   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
   <script>
        $(document).ready(function(){
            $("a").click(function(event){
                $.getJSON('http://www.strava.com/api/v1/segments/637215', function(data) {
                    alert(data);
                });
            });
         });
   </script>
 </body>
 </html>

回答1:


For more information as to why your solution will not work as intended, please refer to: Access-Control-Allow-Origin Multiple Origin Domains?

Try using the .ajax method instead with dataType: "jsonp":

$.ajax({
   url: "http://www.strava.com/api/v1/segments/637215",
    dataType: 'jsonp',
    success: function(data){
        console.log(data);
     }
 });

running this gets the following:

{"segment":{"id":637215,"name":"Highway 33 Climb - Matilija Lake to Rose Valley","distance":16779.2,"elevationGain":1101.1,"elevationHigh":1070.9,"elevationLow":289.54,"averageGrade":4.64087,"climbCategory":"1"}}

EXAMPLE

Note that there does seem to be an error with the returned data, but I am able to see it. (Please see Musa's comment below).

EDIT

or you can change:

$.getJSON('http://www.strava.com/api/v1/segments/637215', function(data) {
                    console.log(data);
                });

to:

$.getJSON('http://www.strava.com/api/v1/segments/637215?callback=?', function(data) {
                    console.log(data);
                });

This will cause .getJSON() to use jsonp instead.

If the URL includes the string "callback=?" (or similar, as defined by the server-side API), the request is treated as JSONP instead.

EXAMPLE



来源:https://stackoverflow.com/questions/12430198/unable-to-complete-the-getjson-request

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!