简体   繁体   English

使用jQuery从ASP.Net JSON服务获取数据

[英]Getting data from ASP.Net JSON service with jQuery

I am trying to call the Google Maps geocoding API, to get a formatted address from a lat/long pair, and then log it to the console. 我正在尝试调用Google Maps地理编码API,从lat / long对获取格式化地址,然后将其记录到控制台。 I am trying to get the first 'formatted_address' item that gets returned for a given location. 我正在尝试获取为给定位置返回的第一个'formatted_address'项。 I am simple unable to extract that item from the JSON, I have no idea why. 我很简单无法从JSON中提取该项,我不知道为什么。 The line of code needed to extract the data would be greatly appreciated. 将非常感谢提取数据所需的代码行。

The javascript: 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****/);
        }
    });
}

The C#: 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();
            }
        }

Your JSON is escaped because you're returning a string from your WebMethod , and not letting the built in JavascriptSerializer do it's thing. 您的JSON被转义,因为您从WebMethod返回一个字符串,而不是让内置的JavascriptSerializer做它的事情。

roughly, you're seeing this: 粗略地说,你看到了这个:

"\{ /*data*/ \}"

instead of this: 而不是这个:

{ /*data*/ }

You can fix this by running the returned string through eval() but note that I'm not recommending it... just saying you can 您可以通过eval()运行返回的字符串来解决此问题,但请注意我不推荐它...只是说你可以

EDIT : 编辑

 $.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
    }
});

Again... eval is evil (if you don't 100% trust the source). 再次...... eval是邪恶的 (如果你不100%信任来源)。 I would recommend returning a different data type from your webmethod... 我建议您从webmethod返回不同的数据类型...

EDIT 2 : 编辑2

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

But my real question is why are you doing this with a webservice call to your server? 但我真正的问题是你为什么要通过web服务调用你的服务器呢? You can directly do geocoding from Javascript to google's API https://google-developers.appspot.com/maps/documentation/javascript/examples/geocoding-reverse 您可以直接从Javascript到Google的API进行地理编码https://google-developers.appspot.com/maps/documentation/javascript/examples/geocoding-reverse

I think the API returns something like: 我认为API返回的内容如下:

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

You could try: 你可以尝试:

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

EDIT: Take a look at the API documentation https://developers.google.com/maps/documentation/geocoding/ 编辑:查看API文档https://developers.google.com/maps/documentation/geocoding/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM