當你用ajax傳遞值到伺服器端,如果值中包含特殊字元串如+,&等,在伺服器端擷取的結果可能就會出現差異,因為這些字元有其它用途,如“+”表示串連符,在轉義後你擷取到的就是空格。
可以看看這些特殊字元與十六進位的關係:
+ |
空格 |
/ |
? |
% |
& |
= |
# |
%2B |
%20 |
%2F |
%3F |
%25 |
%26 |
&3D |
%23 |
如果變數中確實需要包含這些特殊字元,請用encodeURIComponent()函數過濾,它會對這些字元編碼,伺服器端是會被自動解碼的,不需要處理。
另外,盡量提交json格式資料 如 {a:"aaa", b:"bbb"} 而非 "a=aaa&b=bbb"
例子
代碼如下 |
複製代碼 |
<script type="text/javascript"> //alert("你好"); function good(){ //alert("您好 Ajax"); var myurl = document.getElementById("txtUrl").value; var mydata = {"URL" : myurl}; alert(myurl); var jsonData = {"ClientName":"愛&國","URL":"http://192.168.1.8:9080/GeoSearch?Request=geo&level=geometry&ClientName=美國"}; $.ajax({ type: "POST", //ContentType: "text/xml;utf-8",//這裡需要加個utf-8 //dataType:"xml", url: "Tserver", //dataType:"xml", data:mydata, //data:jsonData, //data:{"ClientName":"愛&國","URL":"http://192.168.1.8:9080/GeoSearch?Request=geo&level=geometry&ClientName=美國"}, //data: "ClientName=J/&o#愛國美麗&##hn@@@@人&location=Boston", success: function(data, textStatus){ document.getElementById("g").value=data; //alert(data); alert(jsonData); }, error:function (XMLHttpRequest, textStatus, errorThrown) { // 通常 textStatus 和 errorThrown 之中 // 只有一個會包含資訊 //this; // 調用本次AJAX請求時傳遞的options參數 // alert("bad"); alert(textStatus); //alert(errorThrown); } }); } </script> </head> <body> <div id="url"> 資源地址 :<input type="text" size="50" value="" id="txtUrl" /><br /> 資源名字 :<input type="text" size="50" value="" id="txtName" /> </div> <input type="button" value="Ajax請求" onclick=good() /> <br /> <TextArea rows="10" cols="90" id="g"></TextArea> <div> </div> </body> </html> |
伺服器端:
代碼如下 |
複製代碼 |
package test; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; public class Tserver extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet { static final long serialVersionUID = 1L; public Tserver() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); //response.setContentType("text/xml"); //response.setContentType("application/xml"); response.setCharacterEncoding("UTF-8"); request.setCharacterEncoding("UTF-8"); //request.setCharacterEncoding("UTF-8"); //String ServerName = request.getParameter("ClientName"); String ServerName = request.getParameter("URL"); System.out.println(ServerName); String responseText1 = "your name is: "+ServerName+ " for ever from server"; PrintWriter out = response.getWriter(); out.println("<root>"); out.println(responseText1); out.println("</root>"); out.close(); } } |