简体   繁体   中英

Issue while sending special characters in ajax post request

I am facing an issue while sending special characters in ajax POST request, these special characters are not received properly by my servlet where the request is sent. Javascript code:

myAjaxPostrequest=new GetXmlHttpObject();
var parameters1="content="+mainContent;
    myAjaxPostrequest.open("POST", "controller", true);
    myAjaxPostrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    myAjaxPostrequest.send(parameters1);

Servlet code:

String lsContentToSave = aoReq.getParameter("content");
System.out.println(lsContentToSave);

aoReq is HttpServletRequest object.

For eg. if the special character is » it prints »

I have also tried jquery post and still facing the same issue. Please let me know the fix for this.

You tagged jquery-ajax , but the JS code in your question isn't recognizeable as jQuery. Are you really using jQuery ? That look more like a ripoff of the poor w3schools tutorial.

In any way, you need to take the character encoding into account in 2 places. In the client side, when you form-encode the parameter, you should be using encodeURIComponent() . This will apply percent encoding using UTF-8.

var parameters = "content=" + encodeURIComponent(mainContent);
// ...

In the server side, before you get any parameter from the request body, you should set the request encoding to UTF-8 as follows:

request.setCharacterEncoding("UTF-8");
// ...

String content = request.getParameter("content");
// ...

That said, if you were really using jQuery, then you don't need to worry about using encodeURIComponent() in the client side. jQuery will handle it all for you if you're using $.post() function with a data object.

$.post('controller', { 'content': mainContent}, function() {
    // Callback function here.
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM