簡體   English   中英

格式 JSON 響應為 \

[英]format JSON response with \

我正在嘗試格式化 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 的自動完成中的響應。

我應該改用 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 );
                }
            });
        }
    });
});

\是轉義字符,如果它是內容的一部分,則需要自行轉義。

因此, 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"
    }
]

你試過逃避反斜杠嗎?

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

雖然其他響應者指出反斜杠應該是 escaping,如果您要使用 serializeJSON(),它會為您處理 escaping。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM