我正在尝试使用jQuery的$ .parseJSON()将变量转换为JSON,但JSON字符串中的一个值由HTML代码组成。当我删除HTML变量并替换为'test'时,可以使用$ .parseJSON解析变量,并使用可以操作对象的ajax成功发送到php脚本。
我试图弄清楚如何将HTML代码传递给变量并解析它,以使我的PHP脚本可以访问此对象。目前,questionshtml [index]变量正在打破脚本。
我尝试过使用'questionsvalues [index] .replace(“} {”,“},{”);'为了删除双引号和反斜杠,脚本仍然会中断。有人能提供一个解决方案来正确准备好使用$ .parseJSON()解析的html代码吗?
JAVASCRIPT CODE
var questionstype = [];
var questionshtml = [];
var questionsquestion = [];
//Store all questions, types, and html for each fieldset into 3 separate arrays
for(var i=1;i<=formpreviewid;i++)
{
questionsquestion.push($("#formelement_"+i + " legend").text());
questionstype.push($("#formelement_"+i).attr("class"));
questionshtml.push($("#formelement_"+i)[0].outerHTML);
};
//format values for each fieldset into values format in mysql
var questionsvalues = [];
var index = 0;
for(var i=1;i<=formpreviewid;i++)
{
questionsvalues.push('{"question":"'+questionsquestion[index]+'","type":"'+questionstype[index]+'","html":"'+questionshtml[index]+'"}');
index++;
};
//format mysql values into JSON format
var questionsvaluesjson = '{"questions":['+questionsvalues+']}';
questionsvaluesjson = $.parseJSON(questionsvaluesjson);
//convert to json
var jsonArray = JSON.stringify(questionsvaluesjson);
$.ajax({
type: 'POST',
url: '/project/templates/yoo_nano2/php/saveform.php',
data: {'formpreviewhtml': formpreviewhtml, 'jsonArray': jsonArray},
beforeSend:function(){
// this is where we append a loading image
$("#formpreview").append('<div style="z-index:3000;" id="divoverlaycontainer"><div id="loaderoverlay"><div class="center" id="loader"><img src="/project/templates/yoo_nano2/images/loader.gif"></div></div></div>');
}, success:function(data){
alert(data + "Saved form successfully.");
//$('#viewresults').empty();
$('#divoverlaycontainer').remove();
// successful request; do something with the data
//$('#viewresults').html(data);
}, error:function(){
// failed request; give feedback to user
alert("Save was unsuccessful. Please try again.");
$('#divoverlaycontainer').remove();
}
});
});
});