麻烦与jQuery阿贾克斯阅读JSON [英] Trouble with JQuery Ajax reading JSON

查看:102
本文介绍了麻烦与jQuery阿贾克斯阅读JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用jQuery尝试读取JSON和我一直在结束了在错误处理程序。当我检查的DOM我看到的是状态文本下的错误,没有更多的细节。我试着挽救这一个本地文件,并添加了beforeSend部分,以解决基于另一篇文章的潜在MIME的问题。当我在浏览器中打开URL它不产生有效的JSON。

I'm using JQuery to try to read JSON and I keep ending up in the error handler. When 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);}

});

推荐答案

没有什么不对您的code。问题发生,因为你试图执行一个跨域AJAX请求。然而,并非一切都失去了,因为谷歌提供的谷歌地图的JavaScript API V3服务 - 客户端地理编码API

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.

下面满code样品(测试工作)将让您使用您需要的JSON对象。在这个例子中,警报框将显示威廉斯堡,NY,USA - 第一formatted_address

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>

这篇关于麻烦与jQuery阿贾克斯阅读JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆