gpt4 book ai didi

php - JSON 响应中的换行符非法标记?

转载 作者:行者123 更新时间:2023-11-28 01:59:53 25 4
gpt4 key购买 nike

发回一些 JSON 后,JavaScript 出错:

Uncaught SyntaxError: Unexpected token ILLEGAL 

当我用带有换行符的字符串响应时,例如:

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

This is the PHPthis is the raw JSON response I get back .

是的,我在编码后确实覆盖了一些 JSON。我这样做是为了让客户端知道它必须调用一个函数。我会尝试替代方案。

当我发送没有换行符的响应时,它不会出错。 如何修复换行符?我应该将其转换为什么?如何搜索并替换它?调用 json_encode() 时是否应该使用特殊标志?

我已经尝试过:

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

最佳答案

我可以使用它:

<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

关于php - JSON 响应中的换行符非法标记?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18583636/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com