传递具有特殊字符的字符串 [英] Passing strings having special characters
问题描述
我试图传递带有空格和特殊字符的字符串,但是它出错并且没有任何工作。
例如
< img onclick ='addKeyword(celebritynews& gossip);'src =images / plus.png> ;
但字符串celebritynews& gossip中的'&'正在破坏密码。
我发现问题出在 addKeyword
函数中,我用下面的代码来定义一个名为url的变量, p>
函数addKeyword(categoryId){
var url =addKeyword.php?uid =+ user_id +& categoryId =+ categoryId +& keyword =+ $(#keyword_+ categoryId).attr(value);
}
以及$(#keyword_+ categoryId)导致问题。任何方式来解决这个问题?
假设您在URL上传递字符串,参数值需要进行URL编码。
...汇总编辑...
&
被解释为HTML并且必须是HTML编码的,具体地HTML
< img onclick ='addKeyword(celebritynews& amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; amp; gossip);'src =images / plus.png/ >
JavaScript
使用encodeURIComponent(s) 。
var url =addKeyword.php?uid =+ encodeURIComponent(user_id)+& categoryId =+ encodeURIComponent (categoryId)+& keyword =+ encodeURIComponent($(#keyword_+ categoryId).attr(value));
I am trying to pass strings with spaces and special characters, but its getting error and nothing is working. e.g.
<img onclick='addKeyword("celebritynews&gossip");' src="images/plus.png" >
but the '&' inside string celebritynews&gossip is breaking the code.
I figured out that the problem is in addKeyword
function, I'd used the following code for defining a variable named url,
function addKeyword(categoryId){
var url = "addKeyword.php?uid=" + user_id + "&categoryId=" + categoryId + "&keyword=" + $("#keyword_" + categoryId).attr("value");
}
and that $("#keyword_" + categoryId) is causing problem. Any way to solve that?
Assuming you are passing the string on a URL, the parameter values need to be URL encoded.
...SUMMARY EDIT...
The &
is interpreted as HTML and must be HTML encoded, specifically &
HTML
<img onclick='addKeyword("celebritynews&gossip");' src="images/plus.png" />
JavaScript
Use encodeURIComponent(s).
var url = "addKeyword.php?uid=" + encodeURIComponent(user_id) + "&categoryId=" + encodeURIComponent(categoryId) + "&keyword=" + encodeURIComponent($("#keyword_" + categoryId).attr("value"));
这篇关于传递具有特殊字符的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!