新線

2015-02-11 26 views
1

我有一個AJAX後新線

$.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"); 
} 

沒有幫助。我有點迷路,以確定這個問題的房間原因。

回答

2

我認爲你真的想要做的是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){} 
}); 
1

不要建立由專人使用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() 
     }),