javascript - 未捕获的语法错误 : Unexpected end of JSON input [}

标签 javascript php json

Uncaught Syntax Error: Unexpected end of JSON input

enter image description here

帮助我为什么会收到这样的错误

 $('.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/

相关文章:

javascript - 在多个值后过滤

Javascript 问题已解决,不明白问题出在哪里

php - SQL 'in' 遇到问题

php - 无法使用 mysqli_query 插入数据库

php - 已连接页面PHP的mysqli_query连接

ios - JSONModel:json 到数组?

java - 使用 GSON 从 Java 中的 JSON 字符串获取值

node.js - body-parser,JSON 中位置处出现意外标记 u

javascript函数声明(this.method和method的区别?)

javascript - 如何识别来自 JS 脚本的 http 请求和 HTML<FORM>submit 事件之间的区别