简体   繁体   中英

Passing js object as json to jquery?

I have the following but it's not working, I read somewhere on the stackoverflow that it works like this but I can't seem to get it to work.. it errors... am I doing something wrong?

If I do pass data like this - it works -- so I know my service is working

//THIS WORKS
data: "{one : 'test',two: 'test2' }"


// BUT SETTING UP OBJECT doesn't work..

var saveData = {};
saveData.one = "test";
saveData.two = "tes2";


$.ajax({
    type: "POST",
    url: "MyService.aspx/GetDate",
    data: saveData,
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function(msg) {
        alert(msg.d);
    },
    error: function(msg) {
    alert('error');
    }

});

I believe that code is going to call .value or .toString() on your object and then pass over the wire. You want to pass JSON.

So, include the json javascript library

http://www.json.org/js.html

And then pass...

    var saveData = {};
    saveData.one = "test";
    saveData.two = "tes2";


    $.ajax({
        type: "POST",
        url: "MyService.aspx/GetDate",
        data: JSON.stringify(saveData),      // NOTE CHANGE HERE
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
            alert(msg.d);
        },
        error: function(msg) {
        alert('error');
        }

    });

According to this blog post , the reason it doesn't work when you try to pass the object is that jQuery attempts to serialize it. From the post:

Instead of passing that JSON object through to the web service, jQuery will automatically serialize and send it as:

 fname=dave&lname=ward 

To which, the server will respond with:

 Invalid JSON primitive: fname. 

This is clearly not what we want to happen. The solution is to make sure that you're passing jQuery a string for the data parameter[...]

Which is what you're doing in the example that works.

My suggestion would be to use the jquery-json plug-in and then you can just do this in your code:

...
data: $.toJSON(saveData),
...

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