Passing js object as json to jquery?

后端 未结 3 1472
闹比i
闹比i 2020-12-14 04:06

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 somet

相关标签:
3条回答
  • 2020-12-14 04:16

    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');
            }
    
        });
    
    0 讨论(0)
  • 2020-12-14 04:25

    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.

    0 讨论(0)
  • 2020-12-14 04:32

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

    ...
    data: $.toJSON(saveData),
    ...
    
    0 讨论(0)
提交回复
热议问题