3

Within HTML, it is okay to have endline characters. But when I try to send HTML strings that have endline characters over AJAX to have them operated with JavaScript/jQuery, it returns an error that says that endline characters are illegal. For example, if I have a Ruby string:

"<div>Hello</div>"

and jsonify it with Ruby by to_json, and send it over ajax, parse it within JavaScript by JSON.parse, and insert that in jQuery like:

$('body').append('<div>Hello</div>');

then it does not return an error, but if I do a similar thing with a string like

"<div>Hello\n</div>"

it returns an error. Why are they legal in HTML and illegal in AJAX? Are there any other differences between a legal HTML string loaded as a page and legal HTML string sent over ajax?

4

4 回答 4

2

字符串文字可以包含换行符,它们只需要用反斜杠转义,如下所示:

var string = "hello\
world!";

但是,这不会在字符串中创建换行符,因为它必须是明确的 \n 转义序列。从技术上讲,这将成为 helloworld。正在做

var string = "hello"
+ "world"

会干净得多

于 2013-05-25T22:24:33.040 回答
1

看到您已经通过to_json在 Ruby 中使用正确地转义了 JSON,我相信错误在 jQuery 中;当字符串中有换行符时,很难确定您是要创建单个元素还是文档片段。这会很好用:

var str = "<div>Hello\n</div>";

var wrapper = document.createElement('div');
wrapper.innerHTML = str;

$('body').append(wrapper);

演示

于 2013-05-25T22:32:18.590 回答
1

将 ajax 调用的类型指定为“html”。Jquery 在解析响应时会尝试推断类型。

如果响应是 json,则应转义换行符。

我建议使用库来序列化 json。如果您自己动手,您不太可能处理所有边缘情况。

于 2013-05-25T22:26:26.680 回答
1

JavaScript 中的字符串必须出现在一行中,但转义该行除外:

var str = "abc \
def";

但是请注意,换行符被转义并且不会出现在字符串本身中。

最好的选择是\n,但请注意,如果它已经通过解析的内容,\n那么您需要将其双重转义为\\n.

于 2013-05-25T22:36:31.773 回答