问题
A simple problem that I just can't find the 'right' answer too.
I have a PHP script that reads people's names from a database, and display them in a table. In each row, I have hyperlinked the person's name to a JavaScript function that displays a popup with the person's name as the title - the PHP code and resulting html follows:
$name = $results['name'];
echo '<a href="javascript:void(0)" onclick="popup(this, '\' . $name . '\')">' . $name . '</a>';
With html:
<a href="javascript:void(0)" onclick="popup(this, 'Steve Smith')">Steve Smith</a>
Everything works fine, except when I hit a name that has a hyphen, such as "Bryce D'Arnoud" which results in the apostrophe breaking the html. To get around this issue, I am using the PHP addslashes()
function, resulting in the following code & html:
$name = $results['name'];
echo '<a href="javascript:void(0)" onclick="popup(this, '\' . addslashes($name) . '\')">' . $name . '</a>';
With html:
<a href="javascript:void(0)" onclick="popup(this, 'Bryce D\'Arnoud')">Bryce D'Arnoud</a>
Everything functions fine, but for some reason, the JavaScript is not removing the escape character, and in the popup() function, if I alert out name, I see "Bryce D\'Arnoud"
function popup(t, name) {
alert(name);
}
Any suggestions as to where I am going wrong?
回答1:
First, life would be a lot easier if you didn't mix JavaScript in your markup. Instead, have PHP form semantic markup, and access the data with JavaScript:
$name = $results['name'];
echo '<a href="#" class="popup" data-name="' . $name . '">' . $name . '</a>';
And then access the value (am using jQuery for this for terseness):
$('.popup').click(function(e) {
e.preventDefault();
alert($(this).attr('data-name'));
});
And in native JS (I think):
document.getElementsByClassName('popup').onclick = function (e) {
e = e || window.event;
e.preventDefault();
alert(this.getAttribute('data-name'));
};
回答2:
Wouldn't escaping the double quotes work? (not tested)
echo "<a href=\"javascript:void(0)\" onclick=\"popup(this,'$name')\">$name</a>";
EDIT: Sorry for missing the point. Using preg_replace
to replace the single quotes with their HTML entities might do it, though.
echo '<a href="javascript:void(0)" onclick="popup(this,\'' . preg_replace("/'/",''',$name) . "')\">$name</a>";
EDIT 2 In fact converting all those in $name
might be cleaner:
$name = preg_replace("/'/", ''', $results['name']);
echo "<a href=\"javascript:void(0)\" onclick=\"popup(this,'$name')\">$name</a>";
来源:https://stackoverflow.com/questions/9561040/passing-string-with-apostrophe-from-php-into-javascript-function