Ajax乱码解决方案
2019獨角獸企業重金招聘Python工程師標準>>>
方案1:
??????????? 頁面端:
?<%@ page language="java" contentType="text/html; charset=gb2312"
??? pageEncoding="gb2312"%>
http://www.w3.org/TR/html4/loose.dtd">
Ajax:
function veryfy(){
?//亂碼問題解決:
? //1.頁面端發送的數據采用encodeURI,encodeURI($("#username").val()),服務器端采用new String(str.getBytes("iso8859-1","utf-8"));
?//2.頁面端發送的數據采用兩次encodeURI,encodeURI(encodeURI($("#username").val())),服務器端URLDecoder.decode(str,"utf-8");
?$.get("AjaxSeverlet?name=" + encodeURI($("#username").val()), null, function(data){
??$("#msg").html(data);
?});
?
}
服務器端:
public void doPost(HttpServletRequest request, HttpServletResponse response)
???throws ServletException, IOException {
??? request.setCharacterEncoding("gb2312");???
??? response.setHeader("charset","gb2312");? //設置返回頁面的頭 meta 信息
??? response.setContentType("text/html;charset=gb2312");? //設置輸出的文檔類型
?? // 以上內容在PrintWriter 聲明前設置,杜絕亂碼
????
????????? PrintWriter out=response.getWriter();?
???????
????????? //接收參數實例:(Ajax頁面端到服務器端)
????????? String s = request.getParameter("name");
????????? s = new String(s.getBytes("iso-8859-1"), "utf-8");??
????????? System.out.println(s);
??????????
????????? //服務器端到頁面端:
???????? // out.print("Ajax亂碼解決"); //直接輸出中文?
??????????
????????? /*
?????????? *從數據庫中取中文數據
?????????? */?
????????? SqlTools st = new SqlTools();
????????? ResultSet rs = st.getResultSet("select seller from orders where orderid = 1");
??????????
?????????
????????? String dbs = "";
????????? try {
???if(rs.next()) {
????? dbs = rs.getString("seller");
???? }?
??} catch (SQLException e) {
???// TODO Auto-generated catch block
???e.printStackTrace();
??}
??out.print(dbs);?
?}
?
方案二:
?? 方案一有時候確實不穩定,只需要在頁面端兩次encodeURI,然后在服務器端用URI.decode() 解碼
轉載于:https://my.oschina.net/u/127459/blog/40442
創作挑戰賽新人創作獎勵來咯,堅持創作打卡瓜分現金大獎總結
以上是生活随笔為你收集整理的Ajax乱码解决方案的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【转】Windows Server200
- 下一篇: 常用游戏分析工具 之 PChunter