用jQuery检索包含换行符的JSON格式的文本时出现问题 [英] Problem when retrieving text in JSON format containing line breaks with jQuery
问题描述
在检索JSON格式的文本时遇到一个奇怪的问题.我使用jQuery post
将一些数据(也是JSON格式)发送到服务器(运行PHP),效果很好.然后,当我使用jQuery get
从服务器请求相同的数据时,回调方法将永远不会执行.仅当数据为JSON格式且数据包含换行符时,才会发生这种情况.当我不使用JSON格式时,它可以正常工作.让我感到困惑的是,上传数据没有问题.
I'm having a strange problem when retrieving JSON formatted text. I use jQuery post
to send some data (also JSON formatted) to the server (running PHP) which works fine. Then, when I request the same data from the server using jQuery get
, the callback method never executes. This only occurs when the data is JSON formatted and the data contains a line break. When I don't use JSON formatting it works fine. What baffles me is that there are no problems with uploading the data.
上传代码:(有效)
$.post("ajax/contents_ajax.php", {
'title': caption,
'text': frameText().getContent(),
'image_id': img
},
//Callback
下载代码:(不适用于换行符)
Download code: (doesn't work with line breaks)
$.get("ajax/contents_ajax.php", { 'get_item': id },
function (data){
//Never gets executed if data contains line breaks
}
,'json');
整个问题源于一个事实,即使我启用了该选项,TinyMCE富文本编辑器似乎仍然坚持在所有位置插入换行符
The whole problem stems from the fact that the TinyMCE rich text editor seems to insist on inserting line breaks everywhere, even though I enabled the option
remove_linebreaks : true
我确实希望有换行符,但如果它们破坏了我的代码,则不行.谁能告诉我这里的问题是什么,也许我可以如何使用PHP在服务器上编码换行符?
I do prefer to have line breaks, but not if they break my code. Can anyone tell me what the problem is here, and perhaps how I can encode the linebreaks on the server with PHP?
尽管用''
替换'\n'
的建议不起作用,但它接近正确的解决方案.这段代码删除了令人反感的字符:
While the suggestions to replace '\n'
with ''
did not work, it was close to the right solution. This code removed the offending characters:
function parse($text){
$parsedText = str_replace(chr(10), "", $text);
return str_replace(chr(13), "", $parsedText);
}
推荐答案
如果您想保持换行,可以尝试:
If you would like to keep the line breaks, you might try:
function parse($text) {
// Damn pesky carriage returns...
$text = str_replace("\r\n", "\n", $text);
$text = str_replace("\r", "\n", $text);
// JSON requires new line characters be escaped
$text = str_replace("\n", "\\n", $text);
return $text;
}
这篇关于用jQuery检索包含换行符的JSON格式的文本时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!