I need to manage char like '
in my JSONP request, trought Ajax by jquery. So (from C#) this is what I've done :
myText = "Hello I'm a string";
myText.Replace("'", "\'");
Response.Write(Request["callback"] + "({ htmlModulo: '" + myText + "'});");
but on Client side it broke :
parsererror - SyntaxError: missing } after property list
so, How can I manage '
if the replace doesnt works?
Serializing JSON is already solved for you by .NET. Use System.Web.Script.Serialization.JavaScriptSerializer
:
var serializer = new JavaScriptSerializer();
To construct JSONP you just need to concatenate prefix (either hardcoded or passed in "callback" query parameter) and suffix (normally just )
, but sometimes you may need to pass extra parameters depending on what caller expect like ,42, null)
) with JSON text.
Sample below shows constructing JSONP based on "callback" parameter, replace value of jsonpPrefix
based on your needs.
var myText = "Hello I'm a string";
var jsonpPrefix = Request["callback"] + "(";
var jsonpSuffix = ")";
var jsonp =
jsonpPrefix +
serializer.Serialize(new {htmlModulo = myText}) +
jsonpSuffix);
Response.Write(jsonp);
You should always use a serializer, because doing it yourself means you're more likely to mess up and violate the JSON spec. For example, you are not quoting the key, which is required by JSON, so jQuery and other JSON parsers will be very confused. It will handle all characters that need to be escaped, as well.
More on constructing JSON can be found in How to create JSON string in C#.