3

我正在尝试这样格式化 json 响应:

[
{
    "id": "23029",
    "label": "F:\path\to\file\filename.txt",
    "value": "filename.txt"
},
{
    "id": "23030",
    "label": "F:\path\to\file\filename.txt",
    "value": "filename.txt"
},
{
    "id": "23031",
    "label": "F:\path\to\file\filename.txt",
    "value": "filename.txt"
}

]

但根据JSONLint, \ 正在破坏“结构”?如果我用 | 替换 \ 它有效,所以我知道 \ 是问题所在。我正在使用jQuery 的 Autocomplete中的响应。

我应该改用 SerializeJSON() 吗?如果是这样,我是否需要更改 ajax 自动完成脚本中的某些内容?

$(function() {
    var cache = {},
        lastXhr;
    $( "#media" ).autocomplete({
        minLength: 2,
        source: function( request, response ) {
            var term = request.term;
            if ( term in cache ) {
                response( cache[ term ] );
                return;
            }

            lastXhr = $.getJSON( "ajax/search.cfm", request, function( data, status, xhr ) {
                cache[ term ] = data;
                if ( xhr === lastXhr ) {
                    response( data );
                }
            });
        }
    });
});
4

3 回答 3

8

是转义字符,如果它是内容的一部分,\则需要自行转义。

因此,JSON在客户端接收到它之前,字符串应该是这样的:

[
    {
        "id": "23029",
        "label": "F:\\path\\to\\file\\filename.txt",
        "value": "filename.txt"
    },
    {
        "id": "23030",
        "label": "F:\\path\\to\\file\\filename.txt",
        "value": "filename.txt"
    },
    {
        "id": "23031",
        "label": "F:\\path\\to\\file\\filename.txt",
        "value": "filename.txt"
    }
]
于 2012-04-04T14:10:21.487 回答
8

你试过逃避反斜杠吗?

{
"id": "23030",
"label": "F:\\path\\to\\file\\filename.ext",
"value": "filename.txt"
}
于 2012-04-04T14:11:29.153 回答
4

虽然其他响应者指出您应该转义反斜杠,但如果您使用 serializeJSON() 它会为您处理转义。

于 2012-04-04T19:50:04.843 回答