gpt4 book ai didi

javascript - 无法从数据属性解析 JSON

转载 作者:行者123 更新时间:2023-11-28 14:08:09 25 4
gpt4 key购买 nike

我当前正在尝试从数据属性解析 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com