jQuery getJSON won't work on cross domain

筅森魡賤 提交于 2019-12-11 06:18:20

问题


I'm trying to use google maps' REST api to convert an typed in adress to coordinates. To do so I use jQuery's getJSON function as it uses a native JSONP call.

Though it won't work, it just doesn't get to success, so the alert is never called.

$("#makeCords").click(function(){
    straat = $('#straat').val();
    stad = $('#Stad').val();
    land = $('#Country').val();
    if(straat == "" || stad == "" || land == ""){
        alert("Onvoldoende gegevens! Vul straat, stad en land aan voor het gebruik van de ´bereken coordinaten´ functie.");
    }else{
        $.getJSON("http://maps.google.com/maps/api/geocode/json?callback=?",
        {
            adress: straat +", " + stad +", " + land,
            sensor: "false"
        },
          function(data) {
              alert(data);
          });
    }
});

回答1:


The Google Maps Geocoding API does not support JSON-P; it will ignore your callback parameter, thus cross-domain JSON-P won't work.

You should use official Google Maps Javascript library instead. Internally the library does use JSON-P to pass the information (since it's almost the only way to do cross-domain requests), but that URL is reserved to official library use only.




回答2:


try adding &format=json to your get jason url and chaneg &callback=? to &jsoncallback=?




回答3:


Try jquery jsonp:

$.ajax({
   type: "GET",
   url: "http://url",
   dataType: "jsonp" ,
   success: function (data) {

   }
});



回答4:


Isn't it a kind of security that javascript (in this case jquery) won't ever get or post data outside it's own domain (at least as far as I know javascript is not allowed to post or get cross domains)? You could use a local php script gathering the json information from the google server by curl and send your get-query to this local script. I would give this workaround a try...

Another way would be to use the google maps api for javascript. You could use the gecoding functions from that api to retrieve the latitude and longitude from a given address. So you wouldn't need to make any gets or posts...



来源:https://stackoverflow.com/questions/6557864/jquery-getjson-wont-work-on-cross-domain

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