2011-12-08 95 views
1

我在aspx页面的javascript函数中获取JSON对象。我需要从我的代码隐藏文件中获取这些数据。我该怎么做?如何将JavaScript中的JSON数组传递给我的代码隐藏文件

我的JavaScript函数为:

function codeAddress() 
    { 
     var address = document.getElementById("address").value; 
     var geocoder = new google.maps.Geocoder();    
     geocoder.geocode({ 'address': address }, function(results, status) { 
      if (status == google.maps.GeocoderStatus.OK) { 
       map.setCenter(results[0].geometry.location); 
       var marker = new google.maps.Marker({ map: map, position: results[0].geometry.location }); 
      } 
      else { 
       alert("Geocode was not successful for the following reason: " + status); 
      } 

      var requestParameter = '{' + 
         'output:"' + results + '"}'; 

      $.ajax({ 
       type: "POST", 
       url: "Default.aspx/GetData", 
       data: requestParameter, 
       //contentType: "plain/text", 
       contentType: "application/json; charset=utf-8", 
       dataType: "json", 
       success: function(msg) { 
        alert(msg.d); 

       }, 
       error: function() { alert("error"); } 
      }); 

     }); 
    } 


    Default.aspx.cs 

[WebMethod] 
public static string GetData(Object output) 
{ 
    return output.ToString(); 
} 

我得到的输出对象,而不是实际结果的阵列 - [对象对象],[目标对象],[目标对象]。请提供给我获得实际结果的解决方案。我工作的JSON下面 http://maps.googleapis.com/maps/api/geocode/json?address=M%20G%20Road&sensor=false

+0

的可能重复[如何发布使用JSON,jQuery的复杂对象ASP.NET的数组MVC Controller?](http://stackoverflow.com/questions/320291/how-to-post-an-array-of-complex-objects-with-json-jquery-to-asp-net-mvc-control) –

回答

3

给出创建你的aspx页面一个WebMethod是让页面上的排列为:

[WebMethod] 
public static GetData(type[] arr) // type could be "string myarr" or int type arrary - check this 
{} 

,使JSON请求。

$.ajax({ 
    type: 'POST', 
    url: 'Default.aspx/GetData', 
    data: "{'backerEntries':" + backerEntries.toString() + "}", 
    contentType: 'application/json; charset=utf-8', 
    dataType: 'json', 
    success: function(response) {} 
}); 

或者您可以使用.post()。

在ajax请求中检查url:GetData WebMethod必须在您正在发出ajax请求的页面上的Default.aspx上声明。

检查此问题以了解如何格式化数组以发送到Web方法。
Why doesn't jquery turn my array into a json string before sending to asp.net web method?

检查这些链接以供参考:
Handling JSON Arrays returned from ASP.NET Web Services with jQuery - 最好是采取想法
How to post an array of complex objects with JSON, jQuery to ASP.NET MVC Controller?

相关问题