ajax post json 数据中的新行

new line in ajax post json data

我有一个ajaxpost

$.ajax({
        headers: {
            'Accept': 'application/json',
            'Content-Type': 'application/json'
        },
        type: 'POST',
        url: '${contextPath}/sms/schedule',
        data: '{"id":'+ ($('#idAttribute').val()?$('#idAttribute').val():null) 
                + ',"repId":' + $('#repId').val() + ',"scheduleDate":"' 
                + $('#scheduleDate').val()+ '","scheduleTime":"' 
                + $('#scheduleTime').val() + '","message":"' 
                + $('textarea#message').val() + '"}',
        success: function (data) {
            $('#schedule-sms-modal').modal('hide');
            window.location.replace("${contextPath}/sms/list");
        },
        error : function(jqXHR, textStatus, errorThrown){

        }
    });

文本区域#message 包含新行。所以 Java 后端无法解析请求并给出 400 错误请求。

我尝试了 JSON.stringify($('textarea#message').val()) 并且还用以下函数替换了新行。

var removeEscapeCharacters = function(myJSONString){
    myJSONString.replace(/\n/g, "\n")
            .replace(/\'/g, "\'")
            .replace(/\"/g, '\"')
            .replace(/\&/g, "\&")
            .replace(/\r/g, "\r")
            .replace(/\t/g, "\t")
            .replace(/\b/g, "\b")
            .replace(/\f/g, "\f");
}

没有帮助。我有点迷失了确定这个问题的房间原因。

我认为您真正想要做的是先 stringify() 您的对象,然后将其作为 data 参数传递。

var data = {
    id:           ($('#idAttribute').val() ? $('#idAttribute').val() : null),
    repId:        $('#repId').val(),
    scheduleDate: $('#scheduleDate').val(),
    scheduleTime: $('#scheduleTime').val(),
    message:      $('textarea#message').val()
};

$.ajax({
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    },
    type: 'POST',
    url: '${contextPath}/sms/schedule',
    data: JSON.stringify(data),
    success: function (data) {
        $('#schedule-sms-modal').modal('hide');
        window.location.replace("${contextPath}/sms/list");
    },
    error : function(jqXHR, textStatus, errorThrown){}
});

不要手动构建 JSON 使用 JSON.stringify

       data:JSON.stringify({id: $('#idAttribute').val()?$('#idAttribute').val():null, 
            repId:$('#repId').val(),
            scheduleDate: $('#scheduleDate').val(),
            scheduleTime: $('#scheduleTime').val(),
            message: $('textarea#message').val()
       }),