兩種方式解決jquery Ajax 傳送中文亂碼的方法,
阿新 • • 發佈:2019-01-03
查過網上有很多方法,但很多都不成功,可能是因為在不環境下的區別吧!
首先,必須保證前臺後臺的編碼統一,其次在連線資料庫時的url也要指定編碼。
第一:簡單直接,修改頁面
data:{ username:function(){return ""+name;} },必須以這種方式傳遞引數。name
是要傳的引數。後臺獲取request.getParameter("username");這個username是function前面的username
function conn(name,moduleName,url,url2){ var b; if(name != moduleName){ $.ajax({ type: "post", //使用get方法訪問後臺
dataType: "json", //返回json格式的資料 async: false, //同步 不寫的情況下 預設為true contentType: "application/x-www-form-urlencoded; charset=utf-8", url: "${ctx}/sys/"+url+"-"+url2+"-isExist.action", //要訪問的後臺地址 data:{ name:function(){return ""+name;} }, success: function(data,status){ if(data){//名稱存在時data是false b = true; }else{ alert("名稱已經存在!!!"); b = false; } } });
第二:使用的是進行兩次encodeURI..再發送!
function isFile(){ var fname = document.getElementById("upload").value; var type = document.getElementsByName("type"); for(var i=0;i<type.length;i++){ if(type[i].checked==true){ type = type[i].value; } } fname = fname.substring(fname.lastIndexOf("\\")+1,fname.length) fname = encodeURI(encodeURI(fname)); $j = jQuery.noConflict();//解決JQUERY衝突 //Jquery ajax非同步 // var url= "<%=request.getContextPath()%>/controlDocument/isName.do?fileName="+fname+"&type="+type; // $j.post(url,function(data){ // if(data == "YES"){ // b="000"; // alert("該文件已經存在!覆蓋後不可恢復,確定在覆蓋嗎?"+b); // } // // },"text"); //Jquery ajax 同步 $j.ajax({ async: false, type : "POST", url : "<%=request.getContextPath()%>/controlDocument/isName.do?fileName="+fname+"&type="+type, dataType : 'text', success : function(data) { if(data == "YES"){ if(window.confirm("該文件已經存在!覆蓋後不可恢復,確定在覆蓋嗎?")){ bool = "1"; }else{ bool = "0"; } } } }); } </script>
以下是jsp程式碼
<div align="left">
<fieldset class="fiel_cx">
<legend>檔案上傳</legend>
<form action="/pms/controlDocument/upload.do" method="POST"
enctype="multipart/form-data">
<font color="red">指定檔案檢視人員:</font> <select id="role" name="role">
<option value="">請選擇</option>
<c:forEach items="${kpRoleList}" var="role">
<option value="${role.roleid}">${role.rolelabel}</option>
</c:forEach>
</select> 上傳型別:<input type="radio" name="type" value="1">文件 <input
type="radio" name="type" value="2">視訊 <br> <br>
檔案上傳 <input type="file" name="upload" id="upload" /> <input
type="submit" name="fileCaption" value="上 傳"
onclick="return sub();" />
</form>
</fieldset>
</div>
後臺接收時,要encode一下.
getResponse().setContentType("application/json;charset=utf-8");
getResponse().setHeader("caChe-Control", "no-cache");
getResponse().setCharacterEncoding("UTF-8");
getRequest().setCharacterEncoding("UTF-8");
String fileName = URLDecoder.decode(
getRequest().getParameter("fileName"), "UTF-8");