javascript 未捕获的 SyntaxError:在执行 JSON.Parse 时意外结束输入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24016213/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Uncaught SyntaxError: Unexpected end of input While doing JSON.Parse
提问by Toms Bugna
HTML & PHP:
HTML 和 PHP:
<select id="package">
<?php $package_size_array = array('size_a' => 70, 'size_b' => 90, 'size_c' => 130); ?>
<option value="size" id="<?php echo json_encode($package_size_array, JSON_PRETTY_PRINT); ?>">Size</option>
<!--Some more <option>s here...-->
</select>
JavaScript:
JavaScript:
$(document).ready(function() {
$('select#package').change(function() {
var id = $(this).children(':selected').attr('id');
alert(JSON.parse(id)); /* Line 217. in functions.js file */
});
});
Problem: Chrome and probably other browsers' console prints:
问题:Chrome 可能还有其他浏览器的控制台打印:
Uncaught SyntaxError: Unexpected end of input functions.js:217
(anonymous function) functions.js:217
jQuery.event.dispatch jquery.js:4371
elemData.handle
回答by Quentin
Unless the data you are converting to JSON consists solely of a Boolean or a Number, the resulting JSON is going to contain "
characters.
除非您要转换为 JSON 的数据仅由布尔值或数字组成,否则生成的 JSON 将包含"
字符。
You are using "
characters to delimit your ID attribute value, so the first one in the data is going to end the attribute prematurely.
您使用"
字符来分隔 ID 属性值,因此数据中的第一个字符将过早结束该属性。
This would be much more obvious if you examined the data you were sending to the browser (with view > source
) instead of just looking at the PHP.
如果您检查发送到浏览器的数据(使用view > source
)而不是只查看 PHP,这将更加明显。
You need to convert the text representation of the JSON to an HTML representation of it.
您需要将 JSON 的文本表示形式转换为它的 HTML 表示形式。
id="<?php echo htmlspecialchars(json_encode($package_size_array)); ?>"
You should also remove JSON_PRETTY_PRINT, it is useful for debugging but inefficient in practice and new lines aren't a good fit for attribute values.
您还应该删除 JSON_PRETTY_PRINT,它对调试很有用,但在实践中效率低下,并且新行不适合属性值。
That said, using JSON for an ID value is a terrible idea. If you want to store arbitrary data on an element, use a data-*
attribute(you'll still need to convert the text to HTML though!)
也就是说,将 JSON 用于 ID 值是一个糟糕的主意。如果你想存储元素上的任意数据,使用一个data-*
属性(你仍然需要将文本转换为HTML虽然!)