传递具有特殊字符的字符串 [英] Passing strings having special characters

查看:97
本文介绍了传递具有特殊字符的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图传递带有空格和特殊字符的字符串,但是它出错并且没有任何工作。
例如

 < 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编码的,具体地& amp;


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 &amp;

HTML

<img onclick='addKeyword("celebritynews&amp;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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆