Uncaught Syntax Error: Unexpected end of JSON input
帮助我为什么会收到这样的错误
$('.view-profile').on('click', function(e) {
e.preventDefault();
var id = $(this).data('id');
var str = $(this).data('citizens');
var citizensArray = JSON.parse(str);
alert(citizensArray[0].id);
});
html 和 PHP
<button type="button" class="btn btn-success btn-sm view-profile" data-
citizens="<?php echo json_encode($citizens);?>" data-id="<?php echo
$citizen['id'];?>"><i class="fa fa-fw fa-user-o"></i> Profile</button>
最佳答案
包裹data-citizens
用单引号括起来,即 data-citizen='<?php echo json_encode($citizens);?>'
作为 "
的存在是 JSON 字符串将突然终止属性值。
而且,您不需要使用 JSON.parse()
与 .data()
,如果数据是有效的 JSON 格式,该方法将返回 JavaScript 对象。
When the data attribute is an object (starts with '{') or array (starts with '[') then
jQuery.parseJSON
is used to parse the string; it must follow valid JSON syntax including quoted property names. If the value isn't parseable as a JavaScript value, it is left as a string.
使用JSON.parse()
如果出现上述错误,则返回有效的 JSON 结果。
所以只需使用
var citizensArray = str;
$('.view-profile').on('click', function(e) {
e.preventDefault();
var str = $(this).data('citizens');
console.log(str);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="btn btn-success btn-sm view-profile" data-citizens='{ "id" : 1}'> Profile</button>
关于javascript - 未捕获的语法错误 : Unexpected end of JSON input [},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49357830/