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

标签 javascript php jquery

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

相关文章:

使用 FFMPEG 的 PHP 和 Mysql 当前视频持续时间

javascript - 让 jQuery 'start with' 选择器与构造的对象一起工作

jquery - 使页面 100% 宽度和高度,文本缩放以匹配高度?

php - 在 ajax 请求中使用 JSON 响应更新 JQuery Progressbar

javascript - 我可以在手机屏幕中间放置工具提示吗?

javascript - 我希望 iMacro 继续,除非发现条件错误,否则出现错误消息并退出

javascript - jQuery 在卸载前播放动画?

php - 按日期分组(php、mysql)

javascript - javascript 的调试工具,用于清理未使用的变量、语法错误......

JavaScript JSON : Sum two or more json having only numeric values with same keys