如何转义ajax数据中的特殊字符?

时间:2012-07-26 13:31:31

标签: javascript ajax json jquery

我正在写一个页面并且在成功时我有以下代码:

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等特殊字符?

2 个答案:

答案 0 :(得分: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 ) );
 });

我不确定代码的效率,但看起来它工作正常。

答案 1 :(得分:-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字符串,但是你将显示没有引号或这将是单引号。