【问题标题】:syntax of passing json object using Ajax使用 Ajax 传递 json 对象的语法
【发布时间】:2012-10-04 02:38:06
【问题描述】:

我试图将这些 json 对象传递给后面的代码

var obj = {
        Name: '1',
        Starting: '3',

        Timeline: [
        {
            StartTime: '111',
            GoesFor: '111'

        }
        ,
        {
            StartTime: '112',
            GoesFor: '112'

        }

    ]
    };

当然下一步是对对象进行字符串化

var data = JSON.stringify(obj);

之后我使用 jquery ajax 调用将值传递给后面的代码

$.ajax({
            url: 'default.aspx/test',
            type: 'POST',
            contentType: 'application/json',
            data: data,
            success: function(result) {
                $('#result').html(result.d);
            }
        });

关键是我从 jquery 库中得到错误

POST http://localhost:63050/default.aspx/test 500 (Internal Server Error)

当我删除 obj 变量并将其放入 JSON.stringfy 方法时,问题就解决了,就像这样

var data = JSON.stringify({
            obj: {
                Name: '1',
                Starting: '3',

                Timeline: [
                {
                    StartTime: '111',
                    GoesFor: '111'

                }
                ,
                {
                    StartTime: '112',
                    GoesFor: '112'

                }
                ]
            }
        });

有没有办法将整个对象变量传递给 json.stringify 函数,而不是在函数中声明和初始化?

如果你们想知道,我背后的代码看起来像这样

public class MyModel
{
    public string Name { get; set; }
    public string Starting { get; set; }
    public testing2[] Timeline { get; set; }
}

public class testing2
{
    public string StartTime { get; set; }
    public string GoesFor { get; set; }
}

[WebMethod]
    public static string Test(MyModel obj)
    {
        return "Hello from test" + obj.Name + obj.Starting + obj.Timeline[0].StartTime + obj.Timeline[1].StartTime;
    }

【问题讨论】:

    标签: c# jquery asp.net json


    【解决方案1】:

    不,因为在您的示例中您传递了一个对象,因此您需要将 JSON 数据放入一个对象中,以便将其解析为一个对象。否则你传递的只是一个变量数组。

    基本上,您可以像这样纠正问题:

        $.ajax({
            url: 'default.aspx/test',
            type: 'POST',
            contentType: 'application/json',
            data: { obj: data },
            success: function(result) {
                $('#result').html(result.d);
            }
        });
    

    这样你就可以使用你原来的字符串化了。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-12
      • 2012-11-07
      • 1970-01-01
      • 2012-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多