开发者

Passing JSON data to a webservice

I have two parameters (categoryName and categoryDescription) that I need to pass to the web service using JSON. I found the syntax to pass categoryName but have not been able to get the correct syntax to pass both parameters. Here is the code.

<script src="js/jquery-1.4.1.min.js" type="text/javascript"></script>
<script type="text/javascript">

    $(document).ready(function() {
        $('#hbtnCreateCategory').click(function(event) {
            $.ajax({
                type: "POST",
                url: "lwsServiceData.asmx/CreateHelpDeskCategory",
                data: "{'categoryName': '" + $('#categoryName').val() + "'}",
                contentType: "application/json; charset=utf-8",
              开发者_开发问答  dataType: "json",
                success: function(msg) {
                    AjaxSucceeded(msg);
                },
                error: AjaxFailed
            });

        });

        function AjaxSucceeded(result) {
            alert(result.d);
            $('#result').val = result.d;
        }

        function AjaxFailed(result) {
            alert(result.status + ' ' + result.statusText);
        }

    });
</script> 

Thanks in advance.


Try this:

data: "{ categoryName :'" + $('#categoryName').val() + "' , categoryDescription: '" + $('#categoryDescription').val() + "' }",

Don't forget to update CreateHelpDeskCategory to accept both arguments.

To add a third argument, use the following:

data: "{ categoryName:'" + + $('#categoryName').val() + "' , categoryDescription: '" + + $('#categoryDescription').val() + "', modifiedBy:'jsmith' }",


You should use

data: {categoryName: JSON.stringify($('#categoryName').val()),
       categoryDescription: JSON.stringify($('#categoryDescription').val())}

as a parameter of $.ajax method. The function JSON.stringify can used to serialize any data to JSON (can be downloaded from http://www.json.org/js.html). Manual serialization is not good at least because the possibility that the string which should be serialized contain characters which must be escaped (like '"' or '\' see http://www.json.org/).

Look at also to the another question which I answered before: How do I build a JSON object to send to an AJAX WebService?


data: "{'categoryName': '" + $('#categoryName').val() + "', 'categoryDescription': 'some description'}"

and if it needs to be dynamic:

data: "{'categoryName': '" + $('#categoryName').val() + "', 'categoryDescription': '" + $('#categoryDescription').val() + "'}"


There's also this: http://code.google.com/p/jquery-json/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜