我正在ajax一个页面,成功后我有以下代码:
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 创建。如何修改它或删除上面给出的脚本中的双引号等特殊字符?
最佳答案
我已经做到了。我修改了我的代码:
$(".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 ) );
});
我不确定代码的效率,但看起来效果很好。
关于javascript - 如何转义ajax数据中的特殊字符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11670423/