简体   繁体   中英

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

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.

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 :

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

Better yet, let jQuery handle it for you:

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" ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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