简体   繁体   English

然后使用Json_encode传递给数据属性

[英]Using a Json_encode to then be passed to a data attribute

I'm struggling to set an array to a data attribute. 我正在努力将数组设置为数据属性。 I can see that it is logging in the DOM with the below image ( a complete mess ): 我可以看到它正在使用下面的图像(完整的混乱)登录DOM: 在此处输入图片说明

The attribute data-category is the one in focus. 属性数据类别是重点关注的类别。 My php that is producing this seems to add ='' if there is a space in the converted php array. 如果转换后的php数组中有空格,则产生此错误的php似乎会添加=''。 This is the php that is converting this over to a json array: 这是将其转换为json数组的php:

$arr = array();
foreach($cats as $cat) {
    array_push($arr, $cat->cat_name);
}

data-category="<?php echo json_encode($arr); ?>"

What is it that I'm missing to convert this to a proper json structure for me to work with in the js. 我缺少将其转换为适合在js中使用的json结构的功能是什么。

I'm looking to have an outcome something similar to this: 我正在寻找类似的结果:

Array [ "Customer Service", "Finance", "HR", "Marketing", "Operations", "Sales", "Technology" ]

My php that is producing this seems to add =' 我的PHP正在产生这个似乎添加='

That isn't what the PHP is producing. 那不是PHP产生的。

You are looking at it in a DOM inspector. 您正在DOM检查器中查看它。 That shows the results of parsing the HTML to a DOM and then serialising it back to HTML for display. 这显示了将HTML解析为DOM,然后将其序列化回HTML进行显示的结果。

If you want to look at the output of the PHP then you need to look at View Source and not Inspect Element . 如果要查看PHP的输出,则需要查看View Source而不是Inspect Element


JSON uses " to delimit strings. JSON使用"来分隔字符串。

An HTML attribute value that is delimited by " characters will be terminated by " characters. 由分隔的HTML属性值"的字符将被终止"字符。

To represent a " as data in an HTML attribute value; use &quot; . 要将"表示为HTML属性值中的数据,请使用&quot;

Run the output of json_encode through htmlspecialchars before outputting it into the HTML. 通过htmlspecialchars运行json_encode的输出,然后将其输出到HTML中。

data-category="<?php echo htmlspecialchars(json_encode($arr)); ?>"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM