我当前正在尝试从数据属性解析 JSON,但收到错误:
Uncaught SyntaxError: Unexpected token � in JSON at position 0
这是我的代码:
jQuery( document ).ready( function ( $ ) {
let variations = $( "span" ).data( "variations" );
$( JSON.parse( variations ) ).each( function ( index, variation ) {
console.log( variation );
} );
} );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span data-variations='["\ud83d\udc36","\ud83d\udc31"]'></span>
我不明白。我正在使用此函数在 PHP 中打印 JSON,但我陷入了困境:
<span data-variations='<?= esc_html( json_encode( $variations ) ) ?>'></span>
最佳答案
您遇到此问题是因为 variations
已经具有解析值 as said in the doc :
When a string starts with '{' or '[', then jQuery.parseJSON is used to parse it
jQuery( document ).ready( function ( $ ) {
let variations = $( "span" ).data( "variations" );
$( variations ).each( function ( index, variation ) {
console.log( variation );
} );
} );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span data-variations='["\ud83d\udc36","\ud83d\udc31"]'></span>
关于javascript - 无法从数据属性解析 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60528910/