JQuery won't get json?

前端 未结 5 1476
一向
一向 2020-12-03 12:07

So I\'m trying to complete the simple task of getting json data from google, but this little bit of jquery code won\'t run. Will you please help me figure out why?



        
相关标签:
5条回答
  • 2020-12-03 12:16

    Make sure it's not a cross-domain issue. I guess, for jQuery to be able to call other domain URLs, you need to specify the URL in some special format. I don't exactly remember, but maybe the "?" (question mark) appended in the end of URL?

    0 讨论(0)
  • 2020-12-03 12:18

    I had the same issue. Trying to get json from a server to wich I dind't had access (=> no JSONP).

    I found http://benalman.com/projects/php-simple-proxy/ Add the php proxy to your server and do the ajax call to this file.

    $.ajax({
       type: 'GET',
       url:'proxy.php?url=http://anyDomain.com?someid=thispage',
       dataType: "json",
       success: function(data){
          // success_fn(data);
       },
       error: function(jqXHR, textStatus, errorThrown) {
          // error_fn(jqXHR, textStatus, errorThrown);
       }
    });
    

    where proxy.php (the file from Ben Alman) is hosted in your domain


    Alternative (which I found to be second best to this): http://james.padolsey.com/javascript/cross-domain-requests-with-jquery/

    0 讨论(0)
  • 2020-12-03 12:34

    Try adding &callback=? to your URL string. It may work.

    See this for details > XmlHttpRequest error: Origin null is not allowed by Access-Control-Allow-Origin

    0 讨论(0)
  • 2020-12-03 12:36

    Its called the Same Origin Policy. In short: the domain that your code is on, is the only domain your javascript can communicate with (by default)

    You get an error like this:

    XMLHttpRequest cannot load http://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&sensor=false. Origin http://fiddle.jshell.net is not allowed by Access-Control-Allow-Origin.
    
    0 讨论(0)
  • 2020-12-03 12:40

    Yup, this is absolutely a Same Origin Policy bug.

    It seems that the latest version of the Google Maps API (v3) does not support jsonp. As a result, if you want to geocode, you're going to need to use the maps api:

    <script src="http://code.jquery.com/jquery-latest.js"></script>
    <script src="http://maps.google.com/maps/api/js?sensor=false"></script>
    
    <script>
        $(document).ready(function(){
            var loc = "1600 Amphitheatre Parkway, Mountain View, CA";
            var geocoder = new google.maps.Geocoder();
            geocoder.geocode( {'address': loc },
                function(data, status) { console.log(data); });
        });
    </script>
    

    Other alternatives:

    • Use a 'proxy' service, as ctcherry pointed out, to fetch the data for you.
    • Use the old V2 API with JSONP, but you'll need a Maps API key.
    0 讨论(0)
提交回复
热议问题