简体   繁体   中英

syntax of passing json object using Ajax

Im trying to pass these json object to the code behind

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

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

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

        }

    ]
    };

of course the next step is to stringify the object

var data = JSON.stringify(obj);

after that I use a jquery ajax call to pass the value to code behind

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

the point is im getting error form the jquery library

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

the problem is solved when I remove the obj variable, and put it into the JSON.stringfy method, like this

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

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

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

                }
                ]
            }
        });

Is there anyway to passing the entire object variable into the json.stringify function, instead of declare and initializing within the function?

In case you guys wanted to know, my code behind looks something like this

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;
    }

No, because in your example you are passing in an object, so you need to put the JSON data into an object for it be parsed as an object. Otherwise what you are passing is just an array of variables.

Basically, you could correct the problem like this:

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

That way you can use your original stringify.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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