var dataObj= {
"Cast_Code": "NA",
"Mat_Code": "xxxx",
"Pin_Num": "xxxx",
"MatDetail": [
{
"Batch_Number": "Patch PA",
"Batch_Expiry": "No Expiry",
"Batch_Quantity": "xxx",
"Return_Qty": "0.00"
}
]
}
我正在尝试将上述对象作为属性分配给这样的元素:
content +='<div class="save_data" data-savereturn='+JSON.stringify(dataObj)+'></div>';
但是在查看源代码时,它会出现在 HTML 中,例如:
<div class="save_return" data-savereturn="{"Cast_Code": "NA",...,
"MatDetail": [
{ //Notice the double quote between "Patch PA"
"Batch_Number": "Patch" pa","batch_expiry": "no expiry","batch_quantity": "xxx","return_qty": "0.00""
}
]
}"></div>
我进一步尝试
console.log(JSON.stringify(dataObj));
它将输出正确记录,而不会被双引号破坏,就像将其分配给data-savereturn
.
这个dataObj在jQuery.each循环中创建,然后分配给相应的 HTML 元素。
无法弄清楚 JSON 的中断,即空格后部分的截断和小写。
当单词之间没有空格时不会发生这种情况,即
"Batch_Number": "PatchPA",
更新:
在开始引号双 (")
content +='<div class="save_data" data-savereturn="'+JSON.stringify(dataObj)+'"></div>';
it shows:
<div class="save_return" data-savereturn="{" Cast_Code":"na","Mat_Code":"xyz","Pin_Num":"xyz","batchdetail":[{"batch_number":"patch="" na","batch_expiry":"no="" expiry","batch_quantity":"20","return_qty":"0.00"}]}"=""></div>
jQuery('.selector').data('savereturn')
gives
{
"savereturn": "{"
}
which gives an error on JSON.parse "Uncaught SyntaxError: Unexpected end of JSON input"
将起始引号更改为单引号 (')
content +="<div class='save_data' data-savereturn='"+JSON.stringify(dataObj)+"'></div>";
<div class="save_return" data-savereturn="{"Request_Code":"NA";"Mat_Code":"xx";"In_num":"xx","BatchDetail":[{"Batch_Number":"Batch NA","Batch_Expiry":"No Expiry","Batch_Quantity":"10","Return_Qty":"0.00"}]}"></div>
jQuery('sel').data('savereturn') gives:
{
"Cast_Code": "NA",
"Mat_Code": "tttt",
"Tin_Number": "ppp",
"PatchDetail": [
{
"Batch_Number": "Patch NA",
"Batch_Expiry": "No Expiry",
"Batch_Quantity": "10",
"Return_Qty": "0.00"
}
]
}
which also give error on JSON.parse "Uncaught SyntaxError: Unexpected token o in JSON at position 1"
第二个看起来正确,但 JSON 仍然无效。
很抱歉格式不好。