首页 > 解决方案 > 格式化 json 中的空格错误导致 JQuery 中的“加载”函数中的链接

问题描述

我对 JSON 和 jQuery 有疑问。.load()我想在函数的链接中发送格式化的 JSON 结果。

<?php
$array = array(
    "test1" => "Some_text_without_space",
    "test2" => "Some text with space"
);
$json = json_encode($array);
?>
<div id="test1"></div>
<div id="test2"></div>
<script>
    function Test(value) {
        var obj = JSON.parse(value);
        console.log(obj);
        $('#test1').html(value);
        $('#test2').load('http://example/some_link_even_one_that_doesnt_return_anything.php?json='+value);
    }
    Test('<?php echo $json; ?>');
</script>

当 JSON 结果中没有空格时 - 这很好,但只有当至少有一个空格时才会出现问题,我不知道为什么。

我尝试添加 encodeURIComponent(value) 但它没有改变任何东西,仍然存在错误。

这是控制台:

{test1: "Some_text_without_space", test2: "Some text with space"}
test1: "Some_text_without_space"
test2: "Some text with space"
__proto__: Object

jquery.min.js:2 Uncaught Error: Syntax error, unrecognized expression: text with space"}
    at Function.fa.error (jquery.min.js:2)
    at fa.tokenize (jquery.min.js:2)
    at Function.fa [as find] (jquery.min.js:2)
    at n.fn.init.find (jquery.min.js:2)
    at Object.<anonymous> (jquery.min.js:4)
    at i (jquery.min.js:2)
    at Object.fireWith [as resolveWith] (jquery.min.js:2)
    at z (jquery.min.js:4)
    at XMLHttpRequest.<anonymous> (jquery.min.js:4)

该网站返回此:

<div id="test1">{"test1":"Some_text_without_space","test2":"Some text with space"}</div>
<div id="test2"></div>

标签: javascriptphpjqueryjson

解决方案


示例/测试 JSON 似乎无效。我不认为它会被 PHP 的json_encode.

$json = json_encode(
    [
        "test1" => "Some_text_without_space",
        "test2" => "Some text with space"
    ]
);

var_dump($json);
//string(66) "{"test1":"Some_text_without_space","test2":"Some text with space"}"

JSON.parse()按预期将上面显示的字符串传递给 JavaScript 的工作。您的示例中的 JSON lint 给出:

错误:第 1 行解析错误:{ test1:“Some_text_wi --^ Expecting 'STRING', '}', got 'undefined'

另一种选择是简单地插入 JavaScript 对象而不是字符串。然后,您可以跳过解析函数。

例子:

<script>
  <?= var json = <?= json_encode($array) ?>;
  Test(json); //having removed the parse call.
</script>

推荐阅读