How can I manage ' in a JSONP response?

有些话、适合烂在心里 提交于 2019-12-10 21:26:09

问题


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?


回答1:


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#.




回答2:


leave the text as it is, but use double quotes to escape it in json:

Response.Write(Request["callback"] + "({ htmlModulo: \"" + myText + "\"});");

you could also try this one:

var jsonSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            string json = jsonSerializer.Serialize(yourCustomObject);

and then i leave this as well




回答3:


You would need to do:

myText.Replace("'", "\\'");

If you want an escaped single quote in the value of your htmlModulo property. However, your actual JSON would still be invalid. According to the specification, you should be using double quotes to surround key names and values. Thus, for your response to be valid, you would need to send:

{"htmlModulo": "myText value"}

It really shouldn't matter with JSONP since that relies on inserting a new script element into the DOM. Thus even the improper JSON would be interpreted correctly by the JavaScript interpreter. The problem is if you ever request the data as plain JSON. If you do that, then the way you are sending it now will fail with a variety of libraries. In particular, jQuery will fail silently with improper JSON.



来源:https://stackoverflow.com/questions/9431731/how-can-i-manage-in-a-jsonp-response

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!