I have a Jsp page populated with a few textareas and a submit button which does a ajax GET request. user can type in any text. I'm facing problems when user enters a double quoted string or a string containing backslash. I'm currently using encodeURIComponent and JSON.stringify in that order to prepare the get request url parameters. Is that the proper way to do ? The backend code is receiving improper Json object. Here's a sample
User types: Test "cases" are good
in txtArea0
JS code:
var txtData0 = encodeURIComponent($('#txtArea0').val());
var txtData1 = encodeURIComponent($('#txtArea1').val());
var msg = JSON.stringify([{ "id": 0, "txtData" : txtData0},...]);
However my server is receiving the msg as "[{ "id": 0, "txtData" : "Test "cases" are good"},...]"
I'm totally clueless on why this is happening.
I'm currently using encodeURIComponent and JSON.stringify
That's you're problem.
You should only escape when you're actually building a string in that format.
Since you aren't concatenating the values into a URL, you should not be calling encodeURIComponent
.
If you put the concenate the JSON into a URL, you will need to call encodeURIComponent
on the resulting JSON string, but no earlier.
In summary
You need to apply the correct escaping at the correct time.
Try this,
var txtData0 = $('#txtArea0').val();
var txtData1 = $('#txtArea1').val();
var msg = JSON.stringify([{ "id": 0, "txtData" : txtData0},...]);
Fiddle http://jsfiddle.net/LvGLe/
I had that problem, and I was receiving an exception when triying to deserialized on the server side, I fixed that problem by double escaping ("if that term exists LoL"), please check the function below:
function customEscape(str) {
return encodeURIComponent( str.replace('\"', '\\\"') );
}
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.