日期:2014-05-17 浏览次数:20779 次
?
这里指的所有乱码都是指在文本编辑器里正常,但是在浏览器里乱码。
这里有个例子,可以解决几个问题。
?
浏览器中html乱码 和js乱码 可能是没有<!DOCTYPE html>和<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
html的头很重要,不能写错,甚至引号都不能少。
html文件:(utf-8编码方式存储为.html文本文件 )
<!DOCTYPE html>
<html>
<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<style type="text/css"></style>
<script type="text/javascript">
function deal(data){
alert(data.data[0]);
}
function clicked(){
ajaxPost('../PPHttpServlet',deal,"",true,"json");
//alert("cliked");
}
</script>
<body>嗨
<a href="javascript:clicked()" id="a"> click</a>
</body>
<script type="text/javascript" src="ajaxUtil.js"></script>
</html>
?
ajaxUtil.js文件:(utf-8编码 存储为.js文本文件)
var xmlHttp= false;
function createXMLHttpRequest() {
/* Create a new XMLHttpRequest object to talk to the Web server */
var xmlHttp = false;
/*@cc_on @*/
/*@if (@_jscript_version >= 5)
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
xmlHttp = false;
}
}
@end @*/
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest();
}
return xmlHttp;
}
xmlHttp=createXMLHttpRequest();
/**
* ajaxPost('../PPHttpServlet',deal,"param1=type1¶m2=type2",true,"json");
* @param url the url ,param is permissible.
* @param fun function(data)
* @param params param1=1¶m2=2 . Will be encodeURI twice,please decode once if there are native language.
* @param asyn true:asynchronized else not asynchronized
* @param type text:response text/json : prase responseText to json Object/xml :responseXML
*/
function ajaxPost(url,fun,params,asyn,type) {
if(asyn){
asyn=true;
}else{
asyn=false;
}
xmlHttp.open("POST", url, asyn);
xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlHttp.onreadystatechange = function(){
//alert(xmlHttp.readyState);
if(xmlHttp.readyState == 4) {
//alert(xmlHttp.status);
if(xmlHttp.status == 200) {
if (type=="json") {
var json=null;
try{
json=getJson(xmlHttp.responseText);//xmlHttp.responseText like String:{data:['a','a']}
}catch (e) {
alert(e);
}
//alert(json);
//alert(json.data[1]);
fun(json);
}else if(type=="xml"){
fun(xmlHttp.responseXML);
}else{
fun(xmlHttp.responseText);
}
//alert(xmlHttp.responseText);
}else if(xmlHttp.status == 404) {
try{
//var urlL=window.location.href;
//urlL.subString("");
alert("url unreachable:"+url);
}catch(e){}
}
}
};
if(typeof params!= 'undefined'){
params=encodeURI(params);
params=encodeURI(params);
xmlHttp.send(params);
}else{
xmlHttp.send(null);
}
//alert("posted");
}
function getJson(str){
var json= eval("("+str+")");
return json;
}
?
ajax乱码的话,url参数乱码 可以用下面的设置解决:
??? xmlHttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
?
??? ajax 的param参数乱码 可以在前台进行两次编码 :
??? params=encodeURI(params);
??? params=encodeURI(params);
??? 后台进行一次解码 (前台进行一次编码,后台不解码看起来可以,事实证明不行。)
??? str=URLDecoder.decode(str,"UTF-8");
?
?