Ajax passed parameters contain special characters solution
quote
There is such a problem in JQuery AJAX. The parameters contain special characters, such as &'#@, etc.
This is a problem when executing AJAX, because the passed parameters have changed.
See an example to understand:
- Option One:
- $.ajax({
- url: '/ashx/ajax.ashx',
- type: 'post',
- data: 'option=delete&name=11&adb,
- success: function (data) {
- if (data != 'error') {
- }
- }
- });
- The ajax executed above is to asynchronously delete a data whose name is 11 &abd
- When requesting to the ajax.ashx page, the name parameter we get is 11
- After performing the operation, you will find that the data whose name is 11 is actually deleted , but the data whose name is 11 &abc is not deleted .
- This is due to the & special character, which turns the previous two parameters into three parameters option, name, abc
- Then you need to use another method to pass parameters:
- $.ajax({
- url: '/ashx/ajax.ashx',
- type: 'post',
- data:{ 'option':'delete','name':'11&adb'},
- success: function (data) {
- if (data != 'error') {
- }
- }
- });
- Passing parameters in the above json format can avoid parameter errors caused by special characters.
- Option II:
- 统一编码UTF-8.
- 1.JSP页面:<%@ page language="java" pageEncoding="UTF-8"%>
- 2.Ajax.js页面:传递参数时,可能出现特殊字符的参数用
- escape(encodeURIComponent())两函数进行转码,传递到后台!
- var url = "/ZX/servlet/AddMemoServlet?memo=" + memoCode + "&otherMemo=" + escape (encodeURIComponent(otherMemo)) + "&applNo=" + applNo.innerText.substr(0,16);
- //alert("url="+url);
- xmlHttp.open("POST", url, true);
- xmlHttp.onreadystatechange = doMemo;
- xmlHttp.send(null);
- 3.服务器端接收传递的数据 比如:一个servlet的doGet方法中:
- request.setCharacterEncoding("gb2312");
- response.setContentType("text/xml;charset=utf-8");
- response.setHeader("Cache-Control", "no-cache");
- ......
- //以下解决Ajax中url传递的参数值中包含特殊字符,后端解析出错的问题:以utf-8以方式解码
- java.net.URLDecoder urlDecoder=new java.net.URLDecoder();
- String otherMemo = urlDecoder.decode(request.getParameter("otherMemo"),"utf-8");
- logger.info("otherMemo:" + otherMemo);