所以我向 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("\"",""",$row['title']);
$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>';
关于javascript - 参数编码(引号和空格字符),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38402342/