[英]Extracting data from JSON with ASP.Net web service
我嘗試提取formatted_address屬性失敗。
以下Web服務將以下JSON記錄到控制台。 我無法使用returnedData.d.results[0].formatted_address
獲得格式化的地址。
$.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(returnedData);
}
});
json的格式與Google此處的格式完全相同。
Edit Darin指出,我在矛盾自己:Web服務在廣告對象的上面鏈接中包裝了所有內容,但我沒有提及。
進一步編輯這是Web服務:
[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());
return reader.ReadToEnd();
}
}
這是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)
{
alert(returnedData.d[0].results[0].formatted_address);
console.log(returnedData);
}
});
您是否嘗試過使用不帶.d.
returnedData.results[0].formatted_address
.d.
節點。 那不存在!
刪除“ .d”
returnedData.results[0].formatted_address
但是這樣做總是得到第一個節點
這個問題的答案原來是Web服務正在返回一個字符串,而不是json。 內置的javascript序列化程序無法使用。 需要使用eval關鍵字或更安全的名稱。 碰巧的是,我最終使用了Google Maps Javascript API,無論如何這要容易得多。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.