解決編碼為gb2312頁面ajax互動漢字亂碼問題
ajax只支援utf-8格式,不能支援gb2312編碼格式,所以經常遇到gb2312的編碼的程式使用ajax就出現亂碼,剛找到一種解決方案是:
伺服器端傳送的資料仍是gb2312編碼,用戶端用js將漢字轉變成utf8編碼顯示在頁面
search.php教程
<?php
header("content-type: text/html; charset=gb2312");
include './search.htm';
?>
search.htm
<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html; charset=gb2312" />
<title>進階搜尋</title>
</head>
<body>
<h3>進階搜尋</h3>
<form method="post" action="">
學校類型:
<select name="schooltype">
<option value="">全部</option>
<option value="1">小學</option>
<option value="2">初中</option>
</select>
學校名稱:
<select name="sid" id="sid">
<option value="">請選擇學校</option>
</select>
</form>
<script type="text/網頁特效">
function ajax(settings) {
var xhr = window.activexobject ? new activexobject("microsoft.xmlhttp") : new xmlhttprequest(), successed = false;
xhr.open(settings.type, settings.url);
if(settings.type == 'post')
xhr.setrequestheader('content-type', 'application/x-www-form-urlencoded');
xhr.send((!settings.cache ? 'time=' + new date().gettime() + '&' : '') + settings.data);
settings.loader();
settimeout(function() {
if(!successed) {
alert('resquest timeout!');
xhr.abort();
}
}, settings.timeout);
xhr.onreadystatechange = function() {
if (xhr.readystate == 4 && xhr.status == 200) {
settings.callback(xhr.responsetext.replace(/(^s*)|(s*$)/g, ""));
}
successed = true;
}
}
function a(t) {
ajax({
type: 'post',
url: 'ajax.php',
data: 'schooltype=' + t,
timeout: 8000,
cache: true,
loader: function() {},
callback: function(d) {
var arr = eval(d);
if(typeof(arr) == 'object') {
var obj, option;
document.getelementbyid('sid').innerhtml = '';
for(var i = 0; obj = arr; i ++) {
option = document.createelement('option');
option.value = obj[0];
option.innerhtml = txt2utf8(obj[1], '&#');
document.getelementbyid('sid').appendchild(option);
}
}
}
})
}
function txt2utf8(string, prefix){
for(var i=0,utf8=[];i<string.length;utf8.push((prefix||'u')+string.charcodeat(i++)));
return utf8.join('');
}
a(0);
</script>
</body>
</html>
ajax.php
<?php
header("content-type: text/html; charset=gb2312");
$schooltype = !empty($_post['schooltype']) ? $_post['schooltype'] : 0;
switch($schooltype) {
case 0:
echo "[['40', '太平溪鎮花栗包完全小學'],['41', '太平溪鎮長嶺黑龍江希望小學'],['42', '樂天溪鎮初級中學'],['43', '樂天溪鎮蓮沱初級中學']]";
break;
case 1:
echo "[['40', '太平溪鎮花栗包完全小學'],['41', '太平溪鎮長嶺黑龍江希望小學']]";
break;
case 2:
echo "[['42', '樂天溪鎮初級中學'],['43', '樂天溪鎮蓮沱初級中學']]";
break;
default:
break;
}
?>