将带有撇号的字符串从PHP传递到JavaScript函数中


Passing string with apostrophe from PHP into JavaScript function

一个简单的问题,我也找不到"正确"的答案。

我有一个PHP脚本,可以从数据库中读取人名,并将其显示在表中。在每一行中,我都将人名超链接到一个JavaScript函数,该函数显示一个以人名为标题的弹出窗口-PHP代码和生成的html如下:

$name = $results['name'];
echo '<a href="javascript:void(0)" onclick="popup(this, ''' . $name . ''')">' . $name . '</a>';

带html:

<a href="javascript:void(0)" onclick="popup(this, 'Steve Smith')">Steve Smith</a>

一切都很好,除了当我碰到一个有连字符的名字时,比如"Bryce D’Arnoud",这会导致撇号破坏html。为了解决这个问题,我使用了PHP addslashes()函数,得到了以下代码&html:

$name = $results['name'];
echo '<a href="javascript:void(0)" onclick="popup(this, ''' . addslashes($name) . ''')">' . $name . '</a>';

带html:

<a href="javascript:void(0)" onclick="popup(this, 'Bryce D''Arnoud')">Bryce D'Arnoud</a>

一切都很好,但出于某种原因,JavaScript没有删除转义符,在popup()函数中,如果我发出名称警报,我会看到"Bryce D'''Arnoud"

function popup(t, name) {
  alert(name);
}

关于我哪里出了问题,有什么建议吗?

首先,如果不在标记中混合JavaScript,生活会轻松很多。相反,让PHP形成语义标记,并使用JavaScript:访问数据

$name = $results['name'];
echo '<a href="#" class="popup" data-name="' . $name . '">' . $name . '</a>';

然后访问值(为了简洁起见,我使用jQuery):

$('.popup').click(function(e) {
    e.preventDefault();
    alert($(this).attr('data-name'));
});

在原生JS中(我认为):

document.getElementsByClassName('popup').onclick = function (e) {
    e = e || window.event;
    e.preventDefault();
    alert(this.getAttribute('data-name'));
};

转义双引号无效吗?(未测试)

echo "<a href='"javascript:void(0)'" onclick='"popup(this,'$name')'">$name</a>";

编辑:很抱歉没有抓住要点。不过,使用preg_replace将单引号替换为HTML实体可能会做到这一点。

echo '<a href="javascript:void(0)" onclick="popup(this,''' . preg_replace("/'/",'&#39;',$name) . "')'">$name</a>";

EDIT 2事实上,转换$name中的所有内容可能更干净:

$name = preg_replace("/'/", '&#39;', $results['name']);
echo "<a href='"javascript:void(0)'" onclick='"popup(this,'$name')'">$name</a>";