【问题标题】:Getting data from ASP.Net JSON service with jQuery使用 jQuery 从 ASP.Net JSON 服务获取数据
【发布时间】:2012-07-03 15:34:00
【问题描述】:

我正在尝试调用 Google Maps 地理编码 API,以从 lat/long 对中获取格式化地址,然后将其记录到控制台。我正在尝试获取为给定位置返回的第一个“formatted_address”项目。 我很简单无法从 JSON 中提取该项目,我不知道为什么。非常感谢提取数据所需的代码行。

javascript:

//Gets the current location of the user
function getLocation()
{
    if (navigator.geolocation)
    {
        navigator.geolocation.getCurrentPosition(showPosition);
    }

}

function showPosition(position)
{
    var latitude = position.coords.latitude;
    var longitude = position.coords.longitude;

    $.ajax({
        type: "POST",
        url: "ReportIncident.aspx/ReverseGeocode",
        data: "{latitude:" + latitude + ",longitude:" + longitude + "}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (returnedData)
        {
         // console.log(/****formatted_address Here Please****/);
        }
    });
}

C#:

        [WebMethod]
        public static string ReverseGeocode(decimal latitude, decimal longitude)
        {
            // Create the web request  

            string url = "http://maps.googleapis.com/maps/api/geocode/json?latlng=" + latitude + "," + longitude +
                         "&sensor=true";
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;

            // Get response  
            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                // Get the response stream  
                StreamReader reader = new StreamReader(response.GetResponseStream());

                // Console application output  
                return reader.ReadToEnd();
            }
        }

【问题讨论】:

标签: c# jquery asp.net


【解决方案1】:

您的 JSON 被转义了,因为您从 WebMethod 返回了一个字符串,而不是让内置的 JavascriptSerializer 这样做。

大致上,您会看到:

"\{ /*data*/ \}"

而不是这个:

{ /*data*/ }

您可以通过eval() 运行返回的字符串来解决此问题,但请注意,我不推荐它...只是说你可以

编辑

 $.ajax({
    type: "POST",
    url: "ReportIncident.aspx/ReverseGeocode",
    data: "{latitude:" + latitude + ",longitude:" + longitude + "}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (returnedData)
    {
        var realReturnedData = eval(returnedData.d);
        //realReturnedData now has the google maps data structure you're expecting
    }
});

再次... eval 是邪恶的(如果您不 100% 信任来源)。我建议从您的网络方法返回不同的数据类型...

编辑 2

[WebMethod]
public static MyClass ReverseGeocode(decimal lat, decimal long) {
   MyClass obj = new MyClass();
   //do stuff
   return obj;
}

但我真正的问题是,您为什么要通过对服务器的 Web 服务调用来执行此操作?您可以直接从 Javascript 到 google 的 API https://google-developers.appspot.com/maps/documentation/javascript/examples/geocoding-reverse进行地理编码

【讨论】:

  • 我认为你是对的,但是我如何让内置的 javascript 序列化器来做它的事情。
  • 如果您信任来源,使用 eval 没有任何问题。
  • @rossisdead:确实如此。尽管在我的工作中,我还没有发现有必要这样做的案例。关键是重构,如果可能的话不要使用它。鉴于 ASMX/ASPX webmethods 提供的自动序列化,如果使用复杂的(用户定义的)返回类型(这也将使该方法对服务器端代码的其他部分有用),这里肯定没有必要。
  • @BLSully 谢谢,我使用了 javascript API,解决了所有问题。返回一个字符串而不使用 javascript 序列化程序也是 100% 正确的。
【解决方案2】:

我认为 API 返回如下内容:

{
    "results" : [
    {
        "address_components" : [/***/],
        "formatted_address": "..."
        /* other */
    }],
    "status" : "OK"
}

你可以试试:

if(returnedData.results.length > 0) {
    console.log(returnedData.results[0].formatted_address);
}

编辑:查看 API 文档https://developers.google.com/maps/documentation/geocoding/

【讨论】:

  • 我不断收到此错误:未捕获的类型错误:无法读取未定义的属性“0”,即使正在返回数据。
  • @lee:现在我开始怀疑你是否真的收到了预期的数据
  • 我得到了正确的数据:它正在返回我的地址,我只是无法从 JSON 中得到它。
猜你喜欢
  • 1970-01-01
  • 2014-05-20
  • 2013-07-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-08-05
相关资源
最近更新 更多