Jquery unescape response text from java servlet not working properly

爱⌒轻易说出口 提交于 2019-12-25 06:07:22

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!