XMLHTTPREQUEST的数据传输采用utf8编码(老外搞的东西,对中文支持就是差)。如果我们ajax访问的服务器也是自己编写,那么我们可以把服务器设置为utf8那么问题不大,但如果服务器是别人写好的,采用的是gb2312怎么办呢?我找了半天,结合javascript和vbscript终于搞定了。
vbscript代码如下:
- 'Input:要转为gb2312的字符串(utf8)
- 'Output:GB2312码
'###################################
Function convertstr(vIn)
strReturn = ""
For i = 1 To LenB(vIn)
ThisCharCode = AscB(MidB(vIn,i,1))
If ThisCharCode strReturn = strReturn & Chr(ThisCharCode)
Else
NextCharCode = AscB(MidB(vIn,i+1,1))
strReturn = strReturn & Chr(CLng(ThisCharCode) * &H100 + CInt(NextCharCode))
i = i + 1
End If
Next
convertstr = strReturn
End Function
javascript发送ajax请求
- script type="text/javascript">
- var http_request = false;
- /**
- * 功能:查询辽宁软考的准考证信息
- * 参数:输入准考证号
- * 返回:准考证信息页面
- */
- function send_request() { //初始化、指定处理函数、发送请求的函数
- var url=""; //要调用的连接
- if (window.XMLHttpRequest) { //Mozilla 浏览器
- http_request = new XMLHttpRequest();
- if (http_request.overrideMimeType) { //设置MiME类别
- http_request.overrideMimeType("text/html"); //设定以gb2312编码识别数据
- }
- } else if (window.ActiveXObject) { // IE浏览器
- try {
- http_request = new ActiveXObject("Msxml2.XMLHTTP");
- } catch(e) {
- try {
- http_request = new ActiveXObject("Microsoft.XMLHTTP");
- } catch(e) {}
- }
- }
- if (!http_request) { // 异常,创建对象实例失败
- window.alert("不能创建XMLHttpRequest对象实例.");
- return false;
- }
- http_request.onreadystatechange = function() {
- if (http_request.readyState == 4) { // 判断对象状态
- if (http_request.status == 200) { // 信息已经成功返回,开始处理信息
- gb2utf8_data = http_request.responseBody;
- execScript("gb2utf8_data = convertstr(gb2utf8_data)", "VBScript"); //javascript调用vbscript代码的方法
- var resText = gb2utf8_data; //中文信息
- var namepos = resText.indexOf('姓名');
- var zkzhpos = resText.indexOf("准考证号");
- var name = "姓名:" + resText.substr(namepos + 36,3)
- name=name.replace(","");
- var zkzh = "准考证号:" + resText.substr(zkzhpos + 38,12);
- if (document.getElementById("result").innerHTML == "") {
- document.getElementById("result").innerHTML = name + "," + zkzh;
- }else{
- document.getElementById("result").innerHTML = document.getElementById("result").innerHTML +
- "
" + name + "," + zkzh;
- }
- //document.getElementById("result").innerHTML =gb2utf8_data;
- //alert(bytes2BSTR(http_request.responseBody));
- } else { //页面不正常
- document.getElementById("result").innerHTML = "发生错误!访问超时!"
- }
- }
- }
- http_request.open("POST", url, true);
- http_request.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); //这句话必须加,否则数据过不去
- http_request.send("name=value"); //post表单数据
- }
- /script>