MySQL数据库包含引号编码和未编码,它打破了JavaScript [英] MySQL database contains quotes encoded and unencoded and it's breaking javascript

查看:119
本文介绍了MySQL数据库包含引号编码和未编码,它打破了JavaScript的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例数据库值是分配给PHP变量 $ name ' 12345'

Example database value is '12345' which is assigned to a PHP variable $name.

此值用于javacript onclick事件中,例如:

This value is used in a javacript onclick event for example:

onclick="assign('<?php echo $name;?>')

是处理这个问题的最好方法吗?

What is the best way to deal with this?

onclick="assign('<?php echo $name;?>')
// output: onclick="assign(''12345'')

onclick="assign('<?php echo htmlspecialchars($name);?>')
// output: onclick="assign('&#39;12345'')

onclick="assign('<?php echo addslashes($name);?>')
// output: onclick="assign(''12345\'')

onclick="assign('<?php echo htmlspecialchars(addslashes($name));?>')
// output: onclick="assign('&#39;12345\'')

最后一个版本可行,但我认为必须有更好的方法。

The last version works but I'm thinking there must be a better method.

推荐答案

您应该尽可能使用语言感知的转义例程。 addslashes 几乎从来都不是正确的选择。

You should use language aware escaping routines where possible. addslashes is almost never the right choice.

在这种情况下, json_encode 将完成这项工作,因为JSON是描述文字的JavaScript的一个子集。注意,它也会添加引号来表明它是一个字符串。

In this case, json_encode will do the job as JSON is a subset of the bit of JavaScript that describes literals. Note it will also add the quotes to indicate that it is a string.

一旦你使JavaScript安全,你现有的选择 htmlspecialchars 是使JavaScript安全嵌入HTML属性值的正确方法。

Once you make it safe for JavaScript, your existing choice of htmlspecialchars is the right one to make that JavaScript safe for embedding in an HTML attribute value.

onclick="assign(<?php echo htmlspecialchars(json_encode($name));?>)

您也可以考虑使用 data - 属性来存储数据,然后使用 addEventListener 来绑定事件处理程序。

You could also consider using a data- attribute to store the data in, and then binding your event handlers with addEventListener.

这篇关于MySQL数据库包含引号编码和未编码,它打破了JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆