jQuery調用AJAX時Get和post公用的亂碼解決方案執行個體說明

來源:互聯網
上載者:User

以前在新浪部落格寫過js調用AJAX時Get和post的亂碼解決辦法,但是使用js代碼比較繁瑣,我們在使用ajax進行資料互動時可以使用js的一個成熟架構---jQuery。

一個網站的設計,不管是註冊登入還是分頁尋找,都需要提交參數到伺服器以便得到所需的頁面資料。為了減少使用者因重新整理頁面帶來的煎熬,ajax誕生。但是初學者進行項目開發時,會遇到一個很煩人的問題:中文亂碼。

下面我就通過一個簡單的執行個體來告訴大家哪些地方可能會導致亂碼,我們需要通過什麼方式來解決。
我們這個執行個體主要實現使用者註冊時使用者名稱是否正確(已存在),在焦點移開username文本text時,對username進行非同步提交並由servlet進行提取判斷,並將結果返回頁面做出相應提示。

第一步,建立一個web工程(預設GBK格式),取名jQuery_Ajax。在其WebRoot目錄下建立js檔案包,將jquery-1.4.4.js放於其中。

第二步,在src下建立servlet包,並編寫Vali.java 複製代碼 代碼如下:package servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLDecoder;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
importjavax.servlet.http.HttpServletRequest;
importjavax.servlet.http.HttpServletResponse;
public class Vali extends HttpServlet {
@Override
protectedvoid service(HttpServletRequest request, HttpServletResponse response)
throwsServletException, IOException {
StringuserName = URLDecoder.decode(request.getParameter("userName"),"utf-8");
System.out.println(userName);
response.setContentType("text/html;charset=utf-8");
PrintWriter pw =response.getWriter();
if(userName.equals("張三")){
pw.println("錯誤");
}else{
pw.println("正確");
}
}
}

從可從代碼看出,含有編碼格式的語句便是解決亂碼的辦法之一。
在代碼中注意:
1.URLDecoder.decode(request.getParameter("userName"),"utf-8")——將頁面傳來的資料進行格式轉換並提取
2.response.setContentType("text/html;charset=utf-8")——將響應傳回值進行utf-8編碼後返回頁面
3.特別注意2中的轉換需寫在本方法內一切的response之前,否則可能失效
4.本servlet對資料的格式編碼只適合Post方法,若提交方式為GET則提取頁面資料的代碼如下: 複製代碼 代碼如下:request.setCharacterEncoding("utf-8");
StringuserName = request.getParameter("userName");
userName= new String(userName.getBytes("iso-8859-1"),"utf-8");

第三步,編寫簡單註冊頁面ajax.jsp 複製代碼 代碼如下:<%@ page language="java"import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath =request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTDHTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'ajax.jsp' starting page</title>
<metahttp-equiv="pragma" content="no-cache">
<metahttp-equiv="cache-control" content="no-cache">
<metahttp-equiv="expires" content="0">
<metahttp-equiv="keywords"content="keyword1,keyword2,keyword3">
<metahttp-equiv="description" content="This is my page">
<!--
<linkrel="stylesheet" type="text/css"href="styles.css">
-->
<scripttype="text/javascript"src="js/jquery-1.4.4.js"></script>
<scripttype="text/javascript">
function vali(){
$.ajax({
type:"POST",
url:"/jQuery_Ajax/Vali",
data:encodeURI(encodeURI("userName="+$(":text").val())),
success:function(data){
$("span").text(data);
}
});
}
</script>
</head>
<body>
使用者名稱:<inputtype="text" name="userName"onblur="vali();"/><span></span><br/>
密碼:<inputtype="password" name="password" />
</body>
</html>

在代碼中注意:
1.頁面要設定為utf-8,且引入jquery-1.4.4.js
2.ajax通過POST方法傳遞資料,注意data的設定。將返回資料填入span標籤。

如果使用GET方法傳遞頁面資料,js代碼如下: 複製代碼 代碼如下:function vali(){
$.ajax({
type:"GET",
url:"/jQuery_Ajax/Vali",
data:encodeURI("userName="+$(":text").val()),
success:function(data){
$("span").text(data);
}
});
}

最後一步,在web.xml配置servlet和映射 複製代碼 代碼如下:<servlet>
<description>This is the description of my J2EEcomponent</description>
<display-name>This is the display name of my J2EEcomponent</display-name>
<servlet-name>Vali</servlet-name>
<servlet-class>servlet.Vali</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Vali</servlet-name>
<url-pattern>/Vali</url-pattern>
</servlet-mapping>

經過以上代碼的編寫,本註冊驗證的項目已完成,將其部署至tomcat並通過網頁訪問。

最後總結大神的jQuery亂碼問題解決方案
1. 檢查頁面編碼,將頁面編碼設定為utf8,如下:
<metahttp-equiv="content-type" content="text/html;charset=utf-8">
2. 檢查servlet,在doPost或doGet方法中添加如下代碼:
response.setContentType("text/xml;charset=utf-8");
3. 修改tomcat檔案,在TOMCAT_HOME/conf/server.xml檔案中增加URIEncoding=”utf8”:
<Connector port="8080"protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443"URIEncoding="utf-8"/>
4. 在工程中新增過濾器,將編碼方式設定為utf8
經過以上四步操作後,問題依舊。
5. 檢查ie的http header,查看contentType欄位,如下:
contentType:"application/x-www-form-urlencoded"
6.檢查firefox的http header,查看contentType欄位,如下:
contentType:"application/x-www-form-urlencoded;charset=UTF-8"
對比5,6兩步,問題出現。
7.修改jQuery-1.x.x.js檔案,將
contentType:"application/x-www-form-urlencoded"改為下面的代碼
contentType:"application/x-www-form-urlencoded;charset=UTF-8"

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.