2012-07-26 20 views
1

我ajaxing頁面併成功我有以下代碼:如何轉義ajaxed數據中的特殊字符?

success: function(html){ 
var product_json = []; 
data=$(html); 

$(".product_json", data).each(function(){ 
     product_json.push(jQuery.parseJSON($(this).html())); 
}); 
.... 
//code continue 

的json看起來像:

{ 
    "item_logoagenzia": "/resource/loghi/medium/13.gif", 
    "item_description": "Some Bernini ven.." 
} 

它工作正常,如果我有一些字符如雙引號它停止工作。

錯誤的Json的樣子:

{ 
    "item_logoagenzia": "/resource/loghi/medium/13.gif", 
    "item_description": "Some "Bernini" ven.." 
} 

我沒有對JSON創建控制。如何在上面給出的腳本中修改它或刪除特殊字符(如雙重qoutes)?

+1

如果合適的JSON數據服務要返回*有效的* JSON,則應該將這些引號預先轉義。 JSON在哪裏創建?也許,如果你有機會獲得這項服務,那不會是一個如此困難的改變。 – Dutchie432 2012-07-26 13:33:15

+1

如果json是由無法首先釋放出有效的json的人創建的,那麼可能無法通過編程使其成爲有效的json。 – Esailija 2012-07-26 13:33:25

+0

您的問題是您的JSON數據沒有正確轉義值的來源。 – jbabey 2012-07-26 13:34:23

回答

1

我已經完成了。感謝每一位試圖幫助的人。回答我的問題,讓其他人能夠獲益。我修改這個代碼:

$(".product_json", data).each(function(){ 
    product_json.push(jQuery.parseJSON($(this).html())); 
}); 

$(".product_json", data).each(function(){ 
var myString = $(this).html().split('"item_description":"'); 

var myStringDesc = myString[1]; //split the string into two 

myStringDesc = myStringDesc.substring(0, myStringDesc.length - 2); 

myStringDesc = escapeHtml(myStringDesc);//escapeHtml is just function for removing special chars 

var myNewString = eval('('+ myString[0]+'"item_description":"'+ myStringDesc+'"}'+')'); 

myNewString = JSON.stringify(myNewString); 

product_json.push(jQuery.parseJSON(myNewString)); 
}); 

我不知道有關代碼的效率,但它看起來像它工作正常。再次感謝你們。

-3

您的JSON應該是:

{ 
    "item_logoagenzia": "/resource/loghi/medium/13.gif", 
    "item_description": "Some \"Bernini\" ven.." 
} 

編輯:好吧,我沒有看到有關作者不能編輯JSON ...

你可以試試:

$(this).html().replace("\"Bernini\"","\\\"Bernini\\\"") 

但這取決於你在html上收到的

success: function(html){ 
var product_json = []; 
data=$(html); 

$(".product_json", data).each(function(){ 
     product_json.push(jQuery.parseJSON($(this).html().replace("\"Bernini\"","\\\"Bernini\\\""))); 
}); 

另一個可能工作的解決方案是,您可以刪除/替換值中的所有雙引號(第一個和最後一個引號除外)....這樣,您將收到有效的JSON字符串,但是您將顯示不帶引號的描述,用單引號。

+1

海報稱他無法通過JSON創建進行訪問。 – Dutchie432 2012-07-26 13:34:28

+0

這不是很有幫助... – jbabey 2012-07-26 13:34:42

+0

編輯沒有太大的改進。首先它是JSON,而不是HTML,而且只有當數據包含單詞「Bernini」時,響應錯誤地引用報價的唯一時間是非常不可能的。 – JJJ 2012-07-26 13:44:07