javascript - 格式化 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>
解决方案
示例/测试 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>
推荐阅读
- c - 使用 ProtoBuf 将数据流式传输到带有标题的日志文件
- c - %s*%s%s 的“字节”声明和含义
- html - 图片src在不同页面使用时需要更改
- javascript - 在节点 js 的“xlsx-populate”模块中合并单元格
- android - 在调试模式下迁移到 Android R8 后,初始屏幕显示不相关的布局视图而不是初始布局视图
- html - 布局帮助:zIndex 和溢出
- php - 如何将xml字符串作为XML节点插入到PHP中的dom元素中
- javascript - 从数据库加载验证码站点密钥
- ms-word - 关闭词从内部应用程序添加
- android - Android gradle 构建错误“找不到
"