简体   繁体   English

在文本字段中转义双引号

[英]escaping double quotes in text field

I have a Jsp page populated with a few textareas and a submit button which does a ajax GET request. 我有一个Jsp页面,其中填充了一些文本区域和一个提交按钮,该按钮执行ajax GET请求。 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. 我目前正在按顺序使用encodeURIComponent和JSON.stringify来准备获取请求的url参数。 Is that the proper way to do ? 那是正确的方法吗? The backend code is receiving improper Json object. 后端代码接收到不正确的Json对象。 Here's a sample 这是一个样本

User types: Test "cases" are good in txtArea0 用户类型: Test "cases" are good在txtArea0 Test "cases" are good

JS code: JS代码:

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. 但是,我的服务器接收到的味精为"[{ "id": 0, "txtData" : "Test "cases" are good"},...]"我完全不知道为什么会这样。

I'm currently using encodeURIComponent and JSON.stringify 我目前正在使用encodeURIComponent和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 . 由于您没有将值连接到URL中,因此不应调用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. 如果将浓缩的JSON放入URL,则需要在生成的JSON字符串上调用encodeURIComponent ,但不能更早。

In summary 综上所述

Escape methods are not a magic sauce that makes your code work. 转义方法并不是使您的代码正常工作的魔力。

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/ 小提琴 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: 我遇到了这个问题,尝试在服务器端进行反序列化时遇到异常,我通过两次转义来解决了该问题(“如果该术语存在LoL”),请检查以下功能:

function customEscape(str) {
    return encodeURIComponent( str.replace('\"', '\\\"') );
}

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

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