javascript - 参数编码(引号和空格字符)

标签 javascript php encoding

所以我向 JavaScript 函数发送一个字符串参数,问题是空格字符和/或引号。我可以让其中一种方式工作,但不知道如何让两种方式同时工作。

我将encodeURIComponent 和decodeURIComponent 保留在我的示例中,因为我当前使用它们来处理空格。

Javascript:

function alertTitle(title){
    alert(decodeURIComponent(title));
}

PHP:

//...fetching from MySQL
$title = $row['title'];

//If $title content is wrapped in single or double quotes, this will do:
$title = str_replace("\"",""",$row['title']);
//But if it's not, and has spaces, I have to wrap it in quotes for encodeURIComponent:
$title = '\''.$row['title'].'\''; 
//And that obviously gives error in encodeURIComponent if $title happens already to have
// single quotes

//..And sending $title to javascript:
echo '<a onclick="alertTitle(encodeURIComponent('.$title.'));" href="#">Alert</a>';

所以不知何故我也需要转义单引号,或者然后想出一些非常不同的方法。 但这已经很接近了,所以我希望我只是错过了一些简单的事情。

$title 可能是以下示例中的任何一种:

"Title"

"Title with spaces"

'Title'

'Title' with "all combined"

Title "Blaablaa" here

等等。

我们非常欢迎所有提示。谢谢!

最佳答案

只需使用单引号添加预替换:)

//...fetching from MySQL
$title = $row['title'];

//If $title content is wrapped in single or double quotes, this will do:
$title = str_replace("\"","&quot;",$row['title']);
$title = str_replace("\'","&#39;",$row['title']);

//But if it's not, and has spaces, I have to wrap it in quotes for encodeURIComponent:
$title = '\''.$row['title'].'\''; 
//And that obviously gives error in encodeURIComponent if $title happens already to have
// single quotes

//..And sending $title to javascript:
echo '<a onclick="alertTitle(encodeURIComponent('.$title.'));" href="#">Alert</a>';

关于javascript - 参数编码(引号和空格字符),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38402342/

相关文章:

javascript - js insideHTML如何添加自动id?

php - magento 以编程方式构建类别树

javascript - 使用 Javascript AJAX 发送 PHP POST

mysql - dbWriteTable 忽略 UTF-8 编码

silverlight - 在 Silverlight 4 中(在客户端)编码音频(为 AAC)?

javascript - 使用 Google Caja 运行用户提供的 Javascript

javascript - Node.JS Sandbox 包含某些方法和库

php - 在 MySQL 数据库中制作用于编辑字段的表单的快速而肮脏的方法

MySQL 将 ÅäÖ 视为 AAO?

javascript - jQuery 代理不调用异步函数