使用 jQuery 检索包含换行符的 JSON 格式文本时出现问题

发布于 2024-07-10 16:37:44 字数 1048 浏览 10 评论 0原文

我在检索 JSON 格式的文本时遇到一个奇怪的问题。 我使用 jQuery post 将一些数据(也是 JSON 格式)发送到服务器(运行 PHP),效果很好。 然后,当我使用 jQuery get 从服务器请求相同的数据时,回调方法永远不会执行。 仅当数据为 JSON 格式并且数据包含换行符时才会发生这种情况。 当我不使用 JSON 格式时,它工作正常。 令我困惑的是,上传数据没有任何问题。

上传代码:(有效)

$.post("ajax/contents_ajax.php", {
    'title': caption,
    'text': frameText().getContent(),
    'image_id': img
},
//Callback

下载代码:(不适用于换行符)

$.get("ajax/contents_ajax.php", { 'get_item': id },
function (data){
    //Never gets executed if data contains line breaks
}
,'json');

整个问题源于这样一个事实:TinyMCE 富文本编辑器似乎坚持在各处插入换行符,即使我启用了

remove_linebreaks : true

我更喜欢的 选项有换行符,但如果它们破坏了我的代码,则不会。 谁能告诉我这里的问题是什么,以及如何使用 PHP 对服务器上的换行符进行编码?


更新

虽然用 '' 替换 '\n' 的建议不起作用,但它接近正确的解决方案。 此代码删除了有问题的字符:

function parse($text){
    $parsedText = str_replace(chr(10), "", $text);
    return str_replace(chr(13), "", $parsedText);

}

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.

Uploading code: (works)

$.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');

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

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?


Update

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);

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

九命猫 2024-07-17 16:37:45

很简单,试试吧:

<?php
...
function parseline($string){
  $string = str_replace(chr(10), "//n", $string);
  $string = str_replace(chr(13), "//n", $string);
  return $string;
}

echo parseline($string_with_line_breaks);//returns json readable text

我已经测试过了,效果很完美。 无需添加复杂的功能。

Easy, just try:

<?php
...
function parseline($string){
  $string = str_replace(chr(10), "//n", $string);
  $string = str_replace(chr(13), "//n", $string);
  return $string;
}

echo parseline($string_with_line_breaks);//returns json readable text

I have tested it and it works perfect. No need to add complicated functions.

宛菡 2024-07-17 16:37:45

如果其他响应不起作用,则可以删除除空格之外的所有空白字符。

PHP
$text = trim(preg_replace( "/[\\x00-\\x19]+/" , '' , $text));

来自: https://github.com/joomla/joomla-cms/issues/14502

If the other responses didn't work, it's possible to strip all whitespace characters except the space.

PHP
$text = trim(preg_replace( "/[\\x00-\\x19]+/" , '' , $text));

From: https://github.com/joomla/joomla-cms/issues/14502

旧城空念 2024-07-17 16:37:45

您还可以使用

 标记来保留所有换行符和空格。
 我发布这个答案是因为我也遇到了这个问题,为了解决这个问题,我随机决定使用 
 标签而不是 
并解决了问题,尽管在很多地方都有不需要的反斜杠 \

You can also use <pre> tag that will keep all line breaks and white spaces.
I am posting this answer because i also encounter that problem and for solutions i reached to this question and after that I randomly decided to use <pre> tag instead of <div> and that solved by problem although at many places there were unwanted back slashes \

夢归不見 2024-07-17 16:37:44

如果您想保留换行符,您可以尝试:

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;
}

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;
}
夜灵血窟げ 2024-07-17 16:37:44

换行符并不是问题,因为它们需要在 JSON 中正确转义。 如果您可以使用,您可以使用 json_encode 它会自动转义换行符。 如果做不到这一点,您可以使用上面 Pim Jager 的方法,尽管适当的 JSON 编码器是最好的。

Line breaks aren't the issue so much as they need to be properly escaped in JSON. If it's available to you, you can use json_encode which automatically escapes newlines. Failing that, you can use something like Pim Jager's method above, though a proper JSON encoder would be best.

故事和酒 2024-07-17 16:37:44

我在 PHP4 中创建一个类来模拟 json_encode (在 PHP5 中可用)时遇到了这个问题。 这就是我的想法:

class jsonResponse {
    var $response;

    function jsonResponse() {
        $this->response = array('isOK'=>'KO','msg'=>'Undefined');
    }

    function set($isOK, $msg) {
        $this->response['isOK'] = ($isOK) ? 'OK' : 'KO';
        $this->response['msg'] = htmlentities($msg);
    }

    function setData($data=null) {
        if(!is_null($data))
            $this->response['data'] = $data;
        elseif(isset($this->response['data']))
            unset($this->response['data']);
    }

    function send() {
        header('Content-type: application/json');
        echo '{"isOK":"'.$this->response['isOK'].'","msg":'.$this->parseString($this->response['msg']);
        if(isset($this->response['data']))
            echo ',"data":'.$this->parseData($this->response['data']);
        echo '}';
    }

    function parseData($data) {
        if(is_array($data)) {
            $parsed = array();
            foreach ($data as $key=>$value)
                array_push($parsed, $this->parseString($key).':'.$this->parseData($value));
            return '{'.implode(',', $parsed).'}';
        } else
            return $this->parseString($data);
    }

    function parseString($string) {
            $string = str_replace("\\", "\\\\", $string);
            $string = str_replace('/', "\\/", $string);
            $string = str_replace('"', "\\".'"', $string);
            $string = str_replace("\b", "\\b", $string);
            $string = str_replace("\t", "\\t", $string);
            $string = str_replace("\n", "\\n", $string);
            $string = str_replace("\f", "\\f", $string);
            $string = str_replace("\r", "\\r", $string);
            $string = str_replace("\u", "\\u", $string);
            return '"'.$string.'"';
    }
}

我遵循此处提到的规则。
我只使用了我需要的内容,但我认为您可以根据您正在使用的语言的需要进行调整。 我的情况的问题不是像我最初想象的那样与换行符有关,而是与 / 没有被转义有关。 我希望这可以防止其他人因我弄清楚我做错了什么而感到头疼。

I encountered that problem while making a class in PHP4 to emulate json_encode (available in PHP5). Here's what i came up with :

class jsonResponse {
    var $response;

    function jsonResponse() {
        $this->response = array('isOK'=>'KO','msg'=>'Undefined');
    }

    function set($isOK, $msg) {
        $this->response['isOK'] = ($isOK) ? 'OK' : 'KO';
        $this->response['msg'] = htmlentities($msg);
    }

    function setData($data=null) {
        if(!is_null($data))
            $this->response['data'] = $data;
        elseif(isset($this->response['data']))
            unset($this->response['data']);
    }

    function send() {
        header('Content-type: application/json');
        echo '{"isOK":"'.$this->response['isOK'].'","msg":'.$this->parseString($this->response['msg']);
        if(isset($this->response['data']))
            echo ',"data":'.$this->parseData($this->response['data']);
        echo '}';
    }

    function parseData($data) {
        if(is_array($data)) {
            $parsed = array();
            foreach ($data as $key=>$value)
                array_push($parsed, $this->parseString($key).':'.$this->parseData($value));
            return '{'.implode(',', $parsed).'}';
        } else
            return $this->parseString($data);
    }

    function parseString($string) {
            $string = str_replace("\\", "\\\\", $string);
            $string = str_replace('/', "\\/", $string);
            $string = str_replace('"', "\\".'"', $string);
            $string = str_replace("\b", "\\b", $string);
            $string = str_replace("\t", "\\t", $string);
            $string = str_replace("\n", "\\n", $string);
            $string = str_replace("\f", "\\f", $string);
            $string = str_replace("\r", "\\r", $string);
            $string = str_replace("\u", "\\u", $string);
            return '"'.$string.'"';
    }
}

I followed the rules mentionned here.
I only used what i needed but i figure that you can adapt it to your needs in the language your are using. The problem in my case wasn't about newlines as i originally thought but about the / not being escaped. I hope this prevent someone else from the little headache i had figuring out what i did wrong.

淡水深流 2024-07-17 16:37:44

你会得到像
这样的换行符吗? 或者像\n这样的换行符?
但尝试用 PHP 替换它们。

<?php
$string = 'asdfasf<br />asdfasf';
echo str_replace('<br />', '', $strin); // Replace <br /> with '' (nothing)
?>

或查看 urlencode

do you get linebreaks like <br /> or newlines like \n?
But try to replace them with PHP.

<?php
$string = 'asdfasf<br />asdfasf';
echo str_replace('<br />', '', $strin); // Replace <br /> with '' (nothing)
?>

or check out urlencode

爺獨霸怡葒院 2024-07-17 16:37:44

与 Terw 类似,但替换为 \n

<?php
 $json = str_replace('\n', '', $json);
?>

应删除所有换行符,jquery 不应故障转移
标记,但换行符不应出现在 JSON 中。

Like Terw but with replacing \n

<?php
 $json = str_replace('\n', '', $json);
?>

Should remove all line breaks, jquery shouldn't fail over
tags, but line breaks should not be in JSON.

套路撩心 2024-07-17 16:37:44

你试过这个吗

update tablename set field_name_with_\r\n_in_it = replace(field_name_with_\r\n_in_it,"\r\n","<br />")

它对我有用 mysql 5.0.45

Have you tried this

update tablename set field_name_with_\r\n_in_it = replace(field_name_with_\r\n_in_it,"\r\n","<br />")

It worked for me on mysql 5.0.45

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文