如何将对象从HTML传递到JavaScript
如何将html数据属性转换为JavaScript对象?如何将对象从HTML传递到JavaScript,javascript,jquery,node.js,express,ejs,Javascript,Jquery,Node.js,Express,Ejs,如何将html数据属性转换为JavaScript对象? 我尝试使用JSON.parse(),但它出现了一些错误 这是我的字符串数据的结果 { _id: 5f71ea3362749a305427a012, name: 'House With Beauty Backyard', __v: 0 } 当我使用JSON.parse()时,它返回错误 VM5246:2 Uncaught SyntaxError: Unexpected token _ in JSON at position 4
我尝试使用JSON.parse(),但它出现了一些错误
这是我的字符串数据的结果
{
_id: 5f71ea3362749a305427a012,
name: 'House With Beauty Backyard',
__v: 0
}
当我使用JSON.parse()时,它返回错误
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>
$('#dataTable.btn update')。在('click',函数(){
让dataString=$(this.data('category');
log(数据字符串);
让dataJson=JSON.parse(dataString);
log(dataJson);
$(“#更新模式”).model('show');
})
使用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的更多信息:
能否提供一个更准确的问题示例,以及页面的初始状态。第一个示例中的代码是一个对象,而不是字符串,而且它也是无效的对象,因为GUID需要用引号括起来。此外,您需要对其调用
JSON.stringify()
以将其转换为JSON,而不是JSON.parse()