Single-quoted view using jQuery, Ajax, and JSON

I looked around and I'm trying to find an elegant solution to this, and I have not found it yet. I have an ASMX web service in .NET that I am trying to call that requires parameters.

I use client-side jQuery to call the service, and my jQuery code 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); }
});

This works very well if only the name or information contains a characterone quote. Simple enough, because my JSON defines the end of the field value and is a single quote. If one of these fields contains a single quote, all I get is "Internal Server Error", but further testing with Fiddler showed me the results (I will not bother publishing them), indicating a problem with a single quote.

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

+5
source share
1 answer

, JSON , . , .

json.js / , , ", stringify http://www.json.org/js.html.

+9

All Articles