在 jQuery 中,我在 JSON 结果中返回 HTML,我必须转义什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/652997/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:32:06  来源:igfitidea点击:

In jQuery, I am returning HTML in a JSON result, what do I have to escape?

jqueryjson

提问by mrblah

In my Ajaxrequest (using jQuery) I am returning a JSONresponse.

在我的Ajax请求(使用jQuery)中,我返回了一个JSON响应。

So json.Html will have a string of HTML I want to append inside a div.

所以 json.Html 将有一个 HTML 字符串,我想附加到一个 div 中。

On the server side, do I have to escape the HTML at all?

在服务器端,我是否必须完全转义 HTML?

In my MVC action, I am returning:

在我的 MVC 操作中,我返回:

return Content("{html: ???????}, "application/json");

回答by cobbal

An alternative solution would be to simply return the HTML and use jQuery's load():

另一种解决方案是简单地返回 HTML 并使用 jQuery 的load()

$('#someDiv').load('servershtml.html');

To do it your way though, you would need only to escape double quotes and backslashes.

但是,要按照自己的方式进行操作,您只需要转义双引号和反斜杠即可。

The specificationis very readable and short.

规范非常易读且简短。

回答by singpolyma

You only need to add slashes to quotes and slashes (ala \" and \\) when escaping content to be put into a JSON string. HTML characters mean nothing inside a JSON string, so they're fine :)

在将内容转义到 JSON 字符串中时,您只需要在引号和斜杠(ala \" 和 \\)中添加斜杠。HTML 字符在 JSON 字符串中没有任何意义,所以它们很好:)

Of course, make sure your string is itself well-formed (X)HTML so that it doesn't explode when inserted into the div.

当然,请确保您的字符串本身是格式良好的 (X)HTML,以便在插入 div 时不会爆炸。

回答by Alex Peta

When creating JSON with HTML you have to escape then double-quote character, and also the CLRF characterand it will return HTML fine.

使用 HTML 创建 JSON 时,您必须转义双引号字符,以及CLRF 字符,它会很好地返回 HTML。

I worked with a pl/sql in oracle procedure that was called from a AJAX request. If you would like, i can post the implementation.

我在从 AJAX 请求调用的 oracle 过程中使用了 pl/sql。如果你愿意,我可以发布实现。

You should test your output at http://www.jsonlint.com/to see if its valid.

您应该在http://www.jsonlint.com/测试您的输出以查看其是否有效。

So

所以

{
    "id": "1",
    "html_value": "<a href=\"http://www.google.com\">test link returnin html code</a>"
}

is diffrent from

不同于

{
    "id": "1",
    "html_value": "<a href=\"http://www.google.com\">test link returnin
 html code</a>"
}

because of the CLRF character. You should replace that in the server side with &nbsp; or <br/>.

因为 CLRF 字符。您应该在服务器端将其替换为&nbsp; 或<br/>

Hope this helps, Alex

希望这会有所帮助,亚历克斯

回答by JeanValjean

I will post my experience with PHP. I hope it could helps.

我将发布我使用 PHP 的经验。我希望它能有所帮助。

Usually, one use the json_encode()function to encode the data, e.g.:

通常,使用该json_encode()函数对数据进行编码,例如:

json_encode(array('data1' => 'String data with text',
              'data2' => '<a href="www.stackoverflow.com">The Site</a>'));

Since json_encode()works fine only with UTF-8 strings, I suggest to encode every string in UTF-8 through the function utf8_encode(), i.e.

由于json_encode()仅适用于 UTF-8 字符串,我建议通过函数将每个字符串编码为 UTF-8 utf8_encode(),即

json_encode(array(utf8_encode('data1') => utf8_encode('String data with text'),
              utf8_encode('data2') => utf8_encode('<a href="www.stackoverflow.com">The Site</a>')));

Moreover, if you are using special chars (like èand àin Italian words), I suggest to decode the returned json UTF8 encoded HTML. This is particularly useful if you need to use it in an HTML page (e.g. as a result of an AJAX call). To decode through Javascript, use:

此外,如果您使用特殊字符(如意大利语中的èà),我建议对返回的 json UTF8 编码的 HTML 进行解码。如果您需要在 HTML 页面中使用它(例如作为 AJAX 调用的结果),这尤其有用。要通过Javascript解码,请使用:

decodeURIComponent(escape(html));

where htmlis the returned encoded HTML code.

html返回的编码 HTML 代码在哪里。

Regards.

问候。

回答by sieppl

If you are using PHP json_encode does the trick for you:

如果您使用 PHP json_encode 为您做的伎俩:

$htmlSnippet = '<a href="#"></foo>';
return json_encode(array("html" => $htmlSnippet));

In jQuery you either declare the dataType 'json' (see answer above) or decoding by jQuery.parseJSON

在 jQuery 中,您可以声明 dataType 'json'(参见上面的答案)或通过jQuery.parseJSON 进行解码

回答by Ken Browning

If you set the dataTypeconfiguration optionto 'json'then the object passed to the completeevent will be that javascript object. Basically, jQuery will do the work of converting the response content (assuming its properly formatted JSON) to a javascript object. Example...

如果将dataType配置选项设置为,'json'则传递给complete事件的对象将是该 javascript 对象。基本上,jQuery 将完成将响应内容(假设其格式正确的 JSON)转换为 javascript 对象的工作。例子...

$.ajax({
    dataType: 'json',
    complete: function(myJsonObject) {
        alert(myJsonObject.someMember);
    }
}); //$.ajax({

If you're wondering how to generate properly formatted JSON from .net, then I would encourage you to explore Json.NETbecause it makes generating JSON very, very easy.

如果您想知道如何从 .net 生成格式正确的 JSON,那么我鼓励您探索Json.NET,因为它使生成 JSON 变得非常非常容易。