我试图在JSON字符串中转义换行符并失败。变量为newissuedetailsvalue
。
$(newissueshtml).filter('.newissue').each(function () {
var newissuehtml = $(this).html();
var issueguid = $(newissuehtml).find(".issueguid").val();
var newissuetypevalue = $(newissuehtml).find('.newissuetypeinput').val();
newissuesjsonstring += '{"newissuetype":"' + newissuetypevalue + '",';
newissuesjsonstring += '"newissueguid":"' + issueguid + '",';
var newissuedetailsvalue = $(newissuehtml).find('.newissuedetailsinput').val();
newissuedetailsvalue = newissuedetailsvalue.replace(/"/g, '\'');
newissuedetailsvalue = newissuedetailsvalue.replace(/\\/g, ' ');
newissuedetailsvalue = newissuedetailsvalue.replace(/[\\n]/g, 'x')
.replace(/[\\r]/g, 'x')
.replace(/\t/g, 'x');
newissuesjsonstring += '"newissuedetails":"' + newissuedetailsvalue + '",';
var newissueid = $(newissuehtml).find(".newissueid").val();
newissuesjsonstring += '"newissueid":"' + newissueid + '",';
var selectedresolutiondetail = $(newissuehtml).find(".resdetails").val();
newissuesjsonstring += '"selectedresolutiondetail":"' + selectedresolutiondetail + '",';
var resdetailslong = $(newissuehtml).find(".resdetlong").val();
newissuesjsonstring += '"resolutiondetailslong":"' + resdetailslong + '",';
var rescost = $(newissuehtml).find(".rescost").val();
newissuesjsonstring += '"resolutioncost":"' + rescost + '",';
var newissuesourceinput = $(newissuehtml).find(".newissuesourceinput").val();
newissuesjsonstring += '"newissuesource":"' + newissuesourceinput + '",';
var resolutiondate = $(newissuehtml).find(".resdate").val();
newissuesjsonstring += '"resolutiondate":"' + resolutiondate + '"},';
});
newissuesjsonstring = newissuesjsonstring.slice(0, -1);
newissuesjsonstring += ']';
答案 0 :(得分:3)
为什么要手动构建JSON字符串?为什么不使用JSON.stringify并让库句柄为你逃避?
newissuesjsonstring = JSON.stringify({
newissuetype: $(newissuehtml).find('.newissuetypeinput').val(),
newissueguid: $(newissuehtml).find(".issueguid").val(),
newissuedetails: $(newissuehtml).find('.newissuedetailsinput').val(), //no need for manual escaping!
/*...*/
});