0

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"}]
Community
  • 1
  • 1
ke zhang
  • 65
  • 1
  • 10
  • 1
    Why are you using `dataType` as `text` instead of `json`? Also, what encoding are you using? Take a look at [this answer](http://stackoverflow.com/a/553572/2752041), maybe setting the encoding on JavaScript might help. – mathielo May 15 '15 at 01:43
  • because the original response text is not a correct json format, and causing parse error in jquery – ke zhang May 15 '15 at 01:50

1 Answers1

0

This should work:-


    pResponse.setContentType("application/json");
    pResponse.setContentLength(resultsJson.length());
    Writer out = pResponse.getWriter();
    String escapedJsonString = StringEscapeUtils.escapeJavaScript(resultsJson);
    out.println(escapedJsonString);

Monis
  • 918
  • 7
  • 17