我有一个文本框(txtDescription),用户可以在其中取消事件时输入描述。
问题是当文本框中的AJAX中出现一个'撇号'时引发错误。没有撇号,它可以正常工作并保存得很好。
我尝试使用JSON.stringify,但这没有用。
这是我的代码:
$("#btnCancelEvent").click(function () {
var CencelDesc = $("#txtDescription").val();
var user = $("#lblFullName").html();
if (CencelDesc === "") {
alert("Please provide a reason why this schedule event is being canceled.");
return false;
} else {
$.ajax({
type: "POST",
url: "ScheduleOverview.aspx/CancelEvent",
data: "{'ScheduleID': '" + ScheduleID +
"','CentreID': '" + CentreID +
"','CencelDesc': '" + CencelDesc + //this is where the problem occurs
"','user': '" + user + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
swal("Information", "Schedule Event Cancelled.", "success");
$('#CancelSchedule').modal('hide');
}
});
return false;
}
return false;
});
请协助我解决此问题。
答案 0 :(得分:1)
两个问题:
JSON.stringify
为您处理转义等。所以:
$.ajax({
type: "POST",
url: "ScheduleOverview.aspx/CancelEvent",
data: JSON.stringify({ScheduleID: ScheduleID
,CentreID: CentreID
,CencelDesc: CencelDesc
,user: user }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
swal("Information", "Schedule Event Cancelled.", "success");
$('#CancelSchedule').modal('hide');
}
});
侧面说明:该代码中不需要dataType: "json"
。您对响应不做任何事情。实际上,通常,使用dataType
是一种反模式。相反,请确保服务器发送回正确的Content-Type
标头。