未捕获的SyntaxError:JSON输入的意外结束[} [英] Uncaught SyntaxError: Unexpected end of JSON input [}
问题描述
未捕获的语法错误:JSON输入的意外结束
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
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-citizen ='<?php echo json_encode($ citizen);?>'
存在是JSON字符串会突然终止属性值。
Wrap the data-citizens
in single quotes i.e. data-citizen='<?php echo json_encode($citizens);?>'
as existence of "
is JSON string will abruptly terminate the attribute value.
而且,您不需要使用 JSON.parse()
使用 .data()
,如果数据是有效的JSON格式,该方法将返回JavaScript对象。
And, You don't need to use JSON.parse()
with .data()
, if the data is valid JSON format the method will return JavaScript object.
当数据attribute是一个对象(以'{'开头)或数组(以'['开头)然后
jQuery.parseJSON
用于解析字符串;它必须遵循有效的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结果。
Using JSON.parse()
with valid JSON result if above error.
所以只需使用
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>
这篇关于未捕获的SyntaxError:JSON输入的意外结束[}的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!