【问题标题】:How to pass a JSON array in javascript to my codebehind file如何将 javascript 中的 JSON 数组传递给我的代码隐藏文件
【发布时间】:2011-12-08 11:37:19
【问题描述】:

我在 aspx 页面的 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();
}

我将输出作为对象数组而不是实际结果 - [object Object],[object Object],[object Object]。请为我提供获得实际结果的解决方案。我正在处理的 JSON 如下所示 http://maps.googleapis.com/maps/api/geocode/json?address=M%20G%20Road&sensor=false

【问题讨论】:

标签: c# javascript jquery .net json


【解决方案1】:

在您的 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 上声明。

查看此问题以了解如何格式化数组以发送到网络方法。
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?

【讨论】:

    猜你喜欢
    • 2018-12-23
    • 2014-12-28
    • 2019-07-21
    • 2010-10-21
    • 1970-01-01
    • 1970-01-01
    • 2011-12-08
    • 2018-09-02
    • 1970-01-01
    相关资源
    最近更新 更多