撇号导致AJAX方法出现问题

时间:2019-01-25 13:03:49

标签: c# jquery json ajax

我有一个文本框(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;
});

请协助我解决此问题。

1 个答案:

答案 0 :(得分:1)

两个问题:

  1. JSON使用双引号,而不是单引号。
  2. 从不手工制作JSON字符串。相反,构建一个对象,让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标头。