我必须形成一个JSON字符串,其中一个值有新的行字符。这必须转义,然后使用AJAX调用发布。谁能建议一种用JavaScript转义字符串的方法?我没有使用jQuery。


当前回答

使用encodeURIComponent()对字符串进行编码。

例如。var myEscapedJSONString = encodeURIComponent(JSON.stringify(myJSON));

你不需要解码它,因为web服务器会自动做同样的事情。

其他回答

在使用任何形式的Ajax时,Web上似乎缺乏关于从CGI服务器接收到的响应格式的详细文档。这里的一些条目指出,必须转义返回文本或json数据中的换行符,以防止json转换中的无限循环(挂起)(可能是通过抛出未捕获的异常创建的),无论是由jQuery自动完成还是使用Javascript系统或库json解析调用手动完成。

In each case where programmers post this problem, inadequate solutions are presented (most often replacing \n by \\n on the sending side) and the matter is dropped. Their inadequacy is revealed when passing string values that accidentally embed control escape sequences, such as Windows pathnames. An example is "C:\Chris\Roberts.php", which contains the control characters ^c and ^r, which can cause JSON conversion of the string {"file":"C:\Chris\Roberts.php"} to loop forever. One way of generating such values is deliberately to attempt to pass PHP warning and error messages from server to client, a reasonable idea.

根据定义,Ajax在幕后使用HTTP连接。这样的连接使用GET和POST传递数据,这两者都需要对发送的数据进行编码,以避免错误的语法,包括控制字符。

这给了构造解决方案的足够提示(它需要更多的测试):在PHP(发送)端使用rawurlencode来编码数据,在Javascript(接收)端使用unescape来解码数据。在某些情况下,您将把它们应用于整个文本字符串,在其他情况下,您将只应用于JSON中的值。

如果这个想法被证明是正确的,那么可以构造一些简单的例子来帮助各个级别的程序员一劳永逸地解决这个问题。

在JSON.stringify上还有第二个参数。所以,更优雅的解决方案是:

function escape (key, val) {
    if (typeof(val)!="string") return val;
    return val
      .replace(/[\"]/g, '\\"')
      .replace(/[\\]/g, '\\\\')
      .replace(/[\/]/g, '\\/')
      .replace(/[\b]/g, '\\b')
      .replace(/[\f]/g, '\\f')
      .replace(/[\n]/g, '\\n')
      .replace(/[\r]/g, '\\r')
      .replace(/[\t]/g, '\\t')
    ; 
}

var myJSONString = JSON.stringify(myJSON,escape);

最好使用JSON.parse(yourUnescapedJson);

单引号的一个小更新

function escape (key, val) {
    if (typeof(val)!="string") return val;
    return val      
        .replace(/[\\]/g, '\\\\')
        .replace(/[\/]/g, '\\/')
        .replace(/[\b]/g, '\\b')
        .replace(/[\f]/g, '\\f')
        .replace(/[\n]/g, '\\n')
        .replace(/[\r]/g, '\\r')
        .replace(/[\t]/g, '\\t')
        .replace(/[\"]/g, '\\"')
        .replace(/\\'/g, "\\'"); 
}

var myJSONString = JSON.stringify(myJSON,escape);

这是一个旧帖子。但对于那些使用angular.fromJson和JSON.stringify的人来说,它仍然是有帮助的。 已弃用Escape()。 用这个代替,

var uri_enc = encodeURIComponent(uri); //before you post the contents
var uri_dec = decodeURIComponent(uri_enc); //before you display/use the contents.

ref http://www.w3schools.com/jsref/jsref_decodeuricomponent.asp