问题
java code
pResponse.setHeader("content-type", "text/plain;chartset=UTF-8");
pResponse.setContentLength(resultsJson.length());
Writer out = pResponse.getWriter();
String escapedJsonString = StringEscapeUtils.escapeJavaScript(resultsJson);
out.write(escapedJsonString);
The purpose to escape the return text is because there are some accented character in 'resultsJson' and even though I set charset=UTF-8, I still get garbled text from ajax. check this question from me ajax garbled text
ajax code
var option = {
type : 'POST',
url : $('#csrOrderExportform').attr('action'),
data : $('#csrOrderExportform').serialize(),
beforeSend : preAjaxReqest,
dataType:'text',
error : function(data, statustext, error){
$(".searchSubmitBtn").removeAttr("disabled");
setErrorMessage('No Records Found!');
},
success : function(data){
if (data) {
alert(unescape(data));}
}
};
$.ajax(option);
response text
[{\"orderNumber\":\"S301020000\",\"customerFirstName\":\"\u5F20\u79D1\",\"customerLastName\":\"\u5F20\u79D1\",\"orderStatus\":\"PENDING_FULFILLMENT_REQUEST\",\"orderSubmittedDate\":\"May 13, 2015 1:41:28 PM\"}]
after unescape the text from jquery, I am getting the same text.
expected output
[{"orderNumber":"S301020000","customerFirstName":"张科","customerLastName":"张科","orderStatus":"PENDING_FULFILLMENT_REQUEST","orderSubmittedDate":"May 13, 2015 1:41:28 PM"}]
回答1:
This should work:-
pResponse.setContentType("application/json"); pResponse.setContentLength(resultsJson.length()); Writer out = pResponse.getWriter(); String escapedJsonString = StringEscapeUtils.escapeJavaScript(resultsJson); out.println(escapedJsonString);
来源:https://stackoverflow.com/questions/30249319/jquery-unescape-response-text-from-java-servlet-not-working-properly