简体   繁体   English

读取时转义+字符作为ajax数据传递(以防止串联)

[英]Escaping + character when read to passed as ajax data (to prevent concatenation)

I'm reading the value of an input text field and passing it to be used as ajax data 我正在读取输入文本字段的值,并将其传递来用作ajax数据

The field value has a + 字段值带有+

<input name="someval" type="text" value="Receive (+ open)" />

and looks like when parsed with data, it parses the + as a jquery concatenation. 并且看起来像是在解析数据时,它会将+解析为一个jquery串联。

data: 'someval=' + $("input[name=someval]").val(),

This is the first time I notice this behavior. 这是我第一次注意到此行为。

  • First, how do I solve it. 首先,我该如何解决。
  • Second, I have no way of knowing when the output might have these special chars, so is there a known best practice way to escape input so that whenever it happens we're covered? 其次,我无法知道输出何时可能具有这些特殊字符,因此是否存在一种已知的最佳实践来转义输入,以便每当发生输入时都被覆盖?

Thanks 谢谢

Try encodeURIComponent : 尝试encodeURIComponent

'someval=' + encodeURIComponent($("input[name=someval]").val())

Better yet, let jQuery handle it for you: 更好的是,让jQuery为您处理:

data: { someval:$("input[name=someval]").val() }

jQuery will automatically escape your values (and keys) into the correct format (using jQuery.param() ) for the data type (eg "application/x-www-form-urlencoded" ). jQuery将自动将您的值(和键)转义为数据类型(例如"application/x-www-form-urlencoded" )的正确格式(使用jQuery.param() )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM