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

时间:2016-07-15 17:49:22

标签: 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可能是以下示例中的任何一个:

  

“标题”

     

“带空格的标题”

     

'标题'

     

'标题'与“全部合并”

     

标题“Blaablaa”在这里

等等。

所有提示都非常受欢迎。谢谢!

1 个答案:

答案 0 :(得分:0)

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

//...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>';