简体   繁体   English

无法使用JavaScript对JSON对象POST中的双引号进行转义

[英]Can't unescape double quotes in JSON object POST with javascript

I am trying to POST JSON, but the " is coming through escaped as %22 . So where I see this: {%22domain%22:%22asdf.com%22,%22playerClass%22:%22asdf%22,%22adTag%22:%22%22} in the console after POSTing, I want to send it without the double quotes being escaped. So, it should look like this: {"domain":"asdf.com","playerClass":"asdf","adTag":""} 我正在尝试发布JSON,但是"通过%22转义了。因此,我看到的是: {%22domain%22:%22asdf.com%22,%22playerClass%22:%22asdf%22,%22adTag%22:%22%22}在发布后在控制台中,我想发送它而不用双引号引起来,因此,它应如下所示: {"domain":"asdf.com","playerClass":"asdf","adTag":""}

I am looping through the form fields like so: 我正在像这样遍历表单字段:

$.fn.serializeObject = function () {
var o = {};
var a = this.serializeArray();
$.each(a, function () {
    if (o[this.name] !== undefined) {
        if (!o[this.name].push) {
            o[this.name] = [o[this.name]];
        }
        o[this.name].push(this.value || '');
    } else {
        o[this.name] = this.value || '';
    }
});
return o;
};

And storing the result like this: 并像这样存储结果:

var dataString = JSON.stringify($('form').serializeObject());

How can I unescape the " from becomeing %22 ? The correct format is showing up in the result div, but the console log shows the escaped characters in the JSON object. 我怎样才能使"摆脱%22 ?”正确的格式显示在结果div中,但是控制台日志在JSON对象中显示了转义的字符。

JSFIDDLE 的jsfiddle

You are passing the data as part of the url argument which jQuery further treats as a URIcomponent, and escapes. 您将数据作为url参数的一部分传递,jQuery将其进一步视为URI组件并进行转义。

$.ajax({
            type: "POST",
            dataType: "json",
            url: "?" + dataString,
...

Instead, you should pass this as data, then handle it on your server as a part of the form post: 相反,您应该将此作为数据传递,然后作为表单发布的一部分在服务器上进行处理:

$.ajax({
            type: "POST",
            dataType: "json",
            url: "?"
            data: dataString,

Then jQuery won't escape it thinking that it is a URI. 然后jQuery就不会以为它是URI来逃脱它。 Of course, you actually don't need to stringify that data yourself! 当然,您实际上不需要自己对数据进行字符串化处理! Just pass in the native JS object and JQuery will stringify it for you. 只需传入本地JS对象,JQuery就会为您对其进行字符串化。 See http://api.jquery.com/jquery.ajax/#jQuery-ajax-settings . 请参阅http://api.jquery.com/jquery.ajax/#jQuery-ajax-settings

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

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