将JSON数据从php传递到html-data属性,然后传递给Javascript [英] Passing JSON data from php to html-data attribute and then to Javascript
问题描述
我正在创建一个插件,用户在HTML中添加 data -
属性中的自定义设置。设置采用JSON格式。我在Javascript中使用这些设置。
i'm creating a plugin in which the user adds custom settings in data-
attribute in HTML. Settings are in JSON format. I'm using these settings in Javascript.
它已经预览
, base
和路径
属性。 预览
和 base
有字符串值,但路径
是一个路径
对象的数组。
It has got preview
, base
and paths
properties. preview
and base
have string values, but paths
is an array of path
objects.
当我将JSON设置直接添加到HTML中时,它工作正常:
It works fine when i add JSON setting directly into the HTML:
<div data-side="front" data-params='{"preview": "assets/img/products/tshirt/front-preview.png", "base": "assets/img/products/tshirt/front-base.png", "paths": "[{\"name\": \"base\", \"path\": \"M 324.00,33.00 C 324.00,33.00\", \"x\": 92, \"y\": 16, \"height\": 370}, {\"name\": \"collar\", \"path\": \"M 358.00,46.10 C 358.00,46.10\", \"x\": 170, \"y\": 17, \"height\": 21}, {\"name\": \"leftSleeve\", \"path\": \"M 633.17,170.00 C 633.17,170.00\", \"x\": 288, \"y\": 66, \"height\": 131}, {\"name\": \"leftCuff\", \"path\": \"M 595.00,438.00 C 615.47,438.23\", \"x\": 293, \"y\": 172, \"height\": 33}, {\"name\": \"rightSleeve\", \"path\": \"M 142.00,140.00 C 143.46,150.28\", \"x\": 47, \"y\": 64, \"height\": 131}, {\"name\": \"rightCuff\", \"path\": \"M 48.00,375.38 C 48.00,375.38 95.00\", \"x\": 41, \"y\": 166, \"height\": 36}]"}'>
我使用数据获取此值('Params')
jQuery的方法。它的类型是 object
。
I'm getting this value using data('Params')
method of jQuery. Its type is object
.
现在,当我正在尝试 json_encode
一个php数组并将其传递给数据 -
,它已成功添加
Now, when i'm trying to json_encode
a php array and pass it to the data-
, it's added successfully
<div data-side="front" data-params=<?php echo "'".json_encode($dataParams)."'"; ?>>
但现在输入数据('Params')
在Javascript中是 string
。所以,我得到一个JSON解析错误。如果我删除路径
键,其类型将更改为object。
But now typeof data('Params')
in Javascript is string
. So, i'm getting a JSON parse error. If i remove paths
key, its type changes to object.
这是 print_r
我正在编码的数组:
Here's the print_r
of the array that i'm encoding:
Array
(
[preview] => assets/img/products/tshirt/front-preview.png
[base] => assets/img/products/tshirt/front-base.png
[paths] => Array
(
[0] => Array
(
[name] => base
[path] => M 324.00,33.00 C 324.00,33.00
[x] => 92
[y] => 16
[height] => 370
)
... and more path arrays
)
)
所以,如果我包含路径
密钥,为什么它将其类型更改为字符串?有什么方法可以解决吗?
So, why does it changes its type to string if i include paths
key? Any way to solve it?
编辑:
这是输出:
推荐答案
您需要转义数据并处理特殊字符。
You need to escape data and handle special characters.
<div data-side="front" data-params="<?php echo htmlspecialchars(json_encode($dataParams), ENT_QUOTES, 'UTF-8'); ?>">
并使用jQuery获取:
And get it with jQuery:
$('[data-side="front"]').data('params'); // object
这篇关于将JSON数据从php传递到html-data属性,然后传递给Javascript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!