2013-11-01 24 views
0

我不解通過這樣的: 的test.html:jQuery.ajax加入傳遞 '%' 時 '(丟失)' 至JSON響應(PERC符號)

<!DOCTYPE html> 
<meta charset="utf-8"> 

<head> 
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script> 
</head> 

<body> 
    <script> 
    console.log(jQuery.parseJSON('{"key" : "value_%"}')); ## line 10 
    $.ajax(
    { url : "/scripts/test.pl", 
     success : function(resp) {console.log(resp); console.log(jQuery.parseJSON(resp))} 
    } 
    ); 
    </script> 
</body> 

</html> 

/scripts/test.pl:

print '{"key":"value_%"}'; 

輸出:

Object {key: "value_%"} test.html:10 
{"key":"value_%"(MISSING)} test.html:13 
Uncaught SyntaxError: Unexpected token (jquery.min.js:3 

即Ajax響應正在改變JSON文本添加該 '(丟失)' 位和因此使得parseJS開啓失敗。

這是怎麼發生的?我該如何避免這種情況?

M;

回答

0

沒有理由手動調用parseJSON。只需使用dataType選項

$.ajax({ 
    url : "/scripts/test.pl", 
    dataType: "json", 
    success : function(resp) {console.log(resp);} 
    }); 
+0

我手動調用parseJSON來調試問題。如果我設置了dataType,那麼成功的回調將永遠不會被觸發,我會得到一個「parsererror」。無論如何,問題是$ .ajax插入「(MISSING)」位,而不是我如何解析JSON。 – emepyc

+1

您是否在調試工具中檢查過網絡調用的響應?它可能是你的服務器插入這個並可能是有問題的那個。這似乎比jquery ajax函數更有可能出錯。 – Deadron

+0

是的,你碰到了釘子。它是服務器試圖解釋值中的'%'(我在一種printf中迴應腳本響應)。謝謝您的幫助! – emepyc