1

After sending back some JSON, JavaScript errors out with:

Uncaught SyntaxError: Unexpected token ILLEGAL 

when I respond with a string with a line break like:

{ "call": "myFunction("<ul>↵    <li>Passwords are case-sensitive, that is the lower-case letter \"a\" is diffe...")" }

This is the PHP and this is the raw JSON response I get back.

Yes I do override some of the JSON after it has been encoded. I've done this so the clientside knows it has to call a function. I will try alternatives to this.

It doesn't error out when I send a response without a line break. How can I fix the line break? What should I convert it to? How do I search and replace it? Should I use a special flag when I call json_encode()?

I've tried:

$json = str_replace("\r\n", "\n", $json);
$json = str_replace("\r",   "\n", $json);
$json = str_replace("\n",   "\\n", $json);
4

1 回答 1

1

我得到了它的工作:

<script>
<?php
  $json = '{ "call": "myFunction(\\\"<ul>                                                                                                                                 
    <li>Passwords are case-sensitive, that is the lower-case letter \\\"a\\\" is      diffe...\\\")" }';

  $json = str_replace("\n",   "\\\n", $json);
  echo "var str = '".$json."';";
?>

document.write(str);
str = JSON.parse(str);
alert(str.call);
</script>

在我的测试中,对换行符 n 进行三次转义会保持 html 中的格式,但让字符串由 JSON 解析。

-C

于 2013-09-03T04:29:57.423 回答