简体   繁体   English

在ajax调用之前转义JSON字符串中的字符

[英]Escape characters in JSON string before ajax call

I have a JSON string 我有一个JSON字符串

var str = '{'+
            '"name": "John Doe",'+
            '"company": [{"name": "ABC Corp"}, {"name": "XYZ Corp"}],'+
            '"salary": "$200000"'+
           '}';

I make the ajax call as 我打电话给ajax

$.ajax({
     url: 'url',
     type: 'POST',
     context: document.body,
     dataType: 'json',
     data: str,
     success: function(data){},
     error: function(error){}
     });

How can I escape the double quotes inside the JSON array before making the ajax call. 在进行ajax调用之前,如何在JSON数组中转义双引号。

str已经是有效的JSON(根据JSONLint),因此在通过$.ajax发送之前,您无需转义任何内容。

It looks like you're going the wrong way - JSON.stringify is used to turn a JSON object to a string, the method you want is JSON.parse . 看来您走错了路JSON.stringify用于将JSON对象转换为字符串,所需的方法是JSON.parse

So change that to: 因此将其更改为:

$.ajax({
     url: 'url',
     type: 'POST',
     context: document.body,
     dataType: 'json',
     data: JSON.parse(str),
     success: function(data){},
     error: function(error){}
     });

You can also pass a string formatted as JSON to $.ajax and as your string was already valid JSON you could just skip that step entirely: 您还可以将格式为JSON的字符串传递给$ .ajax,并且您的字符串已经是有效的JSON,您可以完全跳过该步骤:

$.ajax({
     url: 'url',
     type: 'POST',
     context: document.body,
     dataType: 'json',
     data: str,
     success: function(data){},
     error: function(error){}
     });

Although you could just build it up as an object to start with if that is easier (It often is than trying to format a string!): 尽管您可以将它构建为一个对象,以使其更容易(通常比尝试格式化字符串更容易!):

var postData = {
   name:'John Doe'
   ... etc
};

$.ajax({
     url: 'url',
     type: 'POST',
     context: document.body,
     dataType: 'json',
     data: postData,
     success: function(data){},
     error: function(error){}
     });

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

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