Home > Web Front-end > JS Tutorial > body text

ajax传送参数含有特殊字符解决方案

WBOY
Release: 2016-06-01 09:54:12
Original
1084 people have browsed it

方案一:

<code class="language-javascript">$.ajax({
    url: '/ashx/ajax.ashx',
    type: 'post',
    data: 'option=delete&name=11&adb, success: function (data) { if (data != 'error ') { } } }); '</code>
Copy after login

上面执行的ajax就是异步删除一个name为 11&abd 的数据 当请求到ajax.ashx页面时,我们获取到的name参数为11 执行操作后会发现其实删除了name 为 11的数据,而没有删除 name 为 11&abc 的数据 这是由于有&特殊字符,把以前的俩个参数变成了三个参数 option,name,abc 这时就需要用另外一种方法传递参数:

<code class="language-javascript">$.ajax({
    url: '/ashx/ajax.ashx',
    type: 'post',
    data: {
        'option': 'delete',
        'name': '11&adb'
    },
    success: function(data) {
        if (data != 'error') {}
    }
});</code>
Copy after login

采用上面的json格式传递参数就可以避免特殊字符引起的参数错误问题.

 

方案二: 统一编码UTF-8.

1.JSP页面:

<code class="language-xml"></code>
Copy after login

2.Ajax.js页面:传递参数时,可能出现特殊字符的参数用 escape(encodeURIComponent())两函数进行转码,传递到后台!

<code class="language-javascript">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); </code>
Copy after login

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);

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template