ajax post json 数据中的新行 [英] new line in ajax post json data
本文介绍了ajax post json 数据中的新行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个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错误请求.
the text area #message
contain new lines. So the Java back end fail to parse the request and give a 400 bad request.
我尝试了 JSON.stringify($('textarea#message').val())
并且还用以下函数替换了新行.
I tried JSON.stringify($('textarea#message').val())
and also replace new line with following function as well.
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");
}
没有帮助.我有点无法确定这个问题的房间原因.
Didn't help. I'm kind of lost to identify the room cause of this issue.
推荐答案
我认为你真正想要做的是 stringify()
首先你的对象,然后将它作为 data
参数.
What I think you really want to do is stringify()
your object first and then pass that as the data
parameter.
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){}
});
这篇关于ajax post json 数据中的新行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文