【问题标题】:Apostrophe causes problems in AJAX method撇号导致 AJAX 方法出现问题
【发布时间】:2019-01-25 13:03:49
【问题描述】:

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

请协助我如何解决此问题。

【问题讨论】:

    标签: c# jquery json ajax


    【解决方案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 标头。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-02-04
      • 1970-01-01
      • 2023-03-27
      • 2017-12-11
      • 1970-01-01
      • 2014-01-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多