如何将对象从 HTML 传递到 JavaScript

How to passing an Object from HTML to JavaScript

如何将html数据属性转换成JavaScript对象?
我尝试使用 JSON.parse() 但出现了一些错误
有我的字符串数据的结果

{
  _id: 5f71ea3362749a305427a012,
  name: 'House With Beauty Backyard',
  __v: 0
}

当我使用 JSON.parse() 时 return 错误

VM5246:2 Uncaught SyntaxError: Unexpected token _ in JSON at position 4

我的 EJS 代码

<a href="javascript:void()" data-category="<%= category[i] %>"><i class="fas fa-edit"></i></a>

我的 JS 代码

<script>
    $('#dataTable .btn-update').on('click', function () {
        let dataString = $(this).data('category');
        console.log(dataString);
        let dataJson = JSON.parse(dataString);
        console.log(dataJson);
        $('#update-modal').modal('show');
    })
</script>

使用JSON.stringify。试试这个代码:

let dataJson = JSON.parse(JSON.stringify(dataString));
console.log(dataJson);

JSON 键和字符串值需要引号 ("")。

这将是具有有效格式的“字符串数据”:

{
  "_id": "5f71ea3362749a305427a012",
  "name": "House With Beauty Backyard",
  "__v": 0
}

如果您将数据格式更改为有效 JSON,解析错误将会消失。(RFC 8259)

在这里您可以找到更多关于 JSON 的信息: https://tools.ietf.org/pdf/rfc8259.pdf