views:

1034

answers:

1

I've looked around and I'm trying to find an elegant solution to this and I'm yet to find one. I have an ASMX web service in .NET that I'm trying to call that requires parameters. I'm using jQuery on the client side to call the service and my jQuery looks something like this:

$.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    url: "/Reviews/HotelReview.asmx/SubmitReview",
    data: "{'name': '" + name + "', " +
        "'info': '" info + "'}",
    processData: true,
    beforeSend: function() { startSubmit(); },
    complete: function() { submitComplete(); },
    error: function(xhr) { submitError(xhr); },
    success: function(msg) { submitSuccess(msg.d); }
});

It works very well, except when either name or info contain the ' character, a single quote. Simple enough because my JSON defines the end of the value of the field is a single quote. When either of these fields contains a single quote all I get is an "Internal Server Error", but further inspection using fiddler showed me the results (I won't bother to post them) indicating the single quote issue.

I've put something in place temporarily to remove the single quotes on the client side and put them back in on the server side, but this is far from elegant. Does anyone else know a more elegant way to escape these single quotes so that my code can work?

Thanks in advance

+5  A: 

the specs say that in JSON you can only use double-quotes around keys and values so try it with double quotes. I am pretty sure your error will be solved.

you may want to use json.js to encode / escape special chars in the actual values so you don't run into problems with values containing " for instance. or the stringify method from http://www.json.org/js.html

olle
Great response, thanks. I used json.js and JSON.encode(myobject) instead of building a string.
Odd
On browsers that support it (all current-version browsers) you should probably prefer the native JSON object (http://blogs.msdn.com/ie/archive/2008/09/10/native-json-in-ie8.aspx) if json.js doesn't do that for you automatically.
EricLaw -MSFT-