开发者

Trouble with JQuery Ajax reading JSON

开发者 https://www.devze.com 2023-03-19 07:22 出处:网络
I\'m using JQuery to try to read JSON and I keep ending up in the error handler. When开发者_JAVA百科 I inspect the DOM all I see is \"error\" under statusText with no more details.I\'ve tried saving t

I'm using JQuery to try to read JSON and I keep ending up in the error handler. When开发者_JAVA百科 I inspect the DOM all I see is "error" under statusText with no more details. I've tried saving this to a local file and have added the beforeSend section to address potential MIME problems based on another post. When I open the url in a browser it does generate valid JSON.

$.ajax({
type : "GET",
url : "http://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=true",
beforeSend : function(x) {
    if (x && x.overrideMimeType) {x.overrideMimeType("application/j-son;charset=UTF-8");}},
dataType : "application/json",
success : function(data) {
    alert("success" + data)},
error : function(y) {alert("failure" + y.statusText);}

});


There is nothing wrong with your code. The problem is occurring because you are trying to perform a cross-domain AJAX request. However, not all is lost because Google provides their Google Maps Javascript API V3 Services - a client-side Geocoding API.

The following full code sample (tested and working) will give you access to the JSON object that you require. In this example, an alert box will display "Williamsburg, NY, USA" - the first formatted_address.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script> 
<script type="text/javascript">
$(document).ready(function() {
    var geocoder = new google.maps.Geocoder();
    var input = "40.714224,-73.961452";
    var latlngStr = input.split(",", 2);
    var lat = parseFloat(latlngStr[0]);
    var lng = parseFloat(latlngStr[1]);
    var latlng = new google.maps.LatLng(lat, lng);
    geocoder.geocode({ 'latLng': latlng }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            if (results[1]) {
                alert(results[1].formatted_address);
            }
        } else {
            alert("Geocoder failed due to: " + status);
        }
    });
});
</script>
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号