asp(JavaScript)自动判断网页编码并转换的代码
编程学习 2021-07-05 10:58www.dzhlxh.cn编程入门
asp转换网页编码的代码,用正则匹配页面的编码声明是gb2312还是别的,然后输出。
完整的示例代码如下:
<%@LANGUAGE="JAVASCRIPT" CODEPAGE="65001"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>JavaScript自动判断网页编码并转换</title>
</head>
<%Server.ScriptTimeout=9999999;
function send_request(url){
var codedtext;
http_request = Server.CreateObject("Microsoft.XMLHTTP");
http_request.Open("GET",url,false);
http_request.Send(null);
if (http_request.ReadyState == 4){
//自动判断编码开始
var charresult = http_request.ResponseText.match(/CharSet=(\S+)\">/i);
if (charresult != null){
var Cset = charresult[1];
}else{Cset = "gb2312"}//对获取不到的网站采用gb2312编码,可自行更改
//自动判断编码结束
codedtext = bytesToBSTR(http_request.Responsebody,Cset);
}else{
codedtext = "Erro";
}
return(codedtext);
}
function bytesToBSTR(body,Cset){
var objstream;
objstream = Server.CreateObject("Adodb.Stream");
objstream.Type = 1;
objstream.Mode = 3;
objstream.Open();
objstream.Write(body);
objstream.Position = 0;
objstream.Type = 2;
objstream.Charset = Cset;
bytesToBSTR = objstream.Readtext;
objstream.Close;
return(bytesToBSTR);
}%>
<body>
<%Response.Write(send_request("https://www.jb51.net/404.htm"))%>
</body>
</html>
代码如下:
<%@LANGUAGE="JAVASCRIPT" CODEPAGE="65001"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>JavaScript自动判断网页编码并转换</title>
</head>
<%Server.ScriptTimeout=9999999;
function send_request(url){
var codedtext;
http_request = Server.CreateObject("Microsoft.XMLHTTP");
http_request.Open("GET",url,false);
http_request.Send(null);
if (http_request.ReadyState == 4){
//自动判断编码开始
var charresult = http_request.ResponseText.match(/CharSet=(\S+)\">/i);
if (charresult != null){
var Cset = charresult[1];
}else{Cset = "gb2312"}//对获取不到的网站采用gb2312编码,可自行更改
//自动判断编码结束
codedtext = bytesToBSTR(http_request.Responsebody,Cset);
}else{
codedtext = "Erro";
}
return(codedtext);
}
function bytesToBSTR(body,Cset){
var objstream;
objstream = Server.CreateObject("Adodb.Stream");
objstream.Type = 1;
objstream.Mode = 3;
objstream.Open();
objstream.Write(body);
objstream.Position = 0;
objstream.Type = 2;
objstream.Charset = Cset;
bytesToBSTR = objstream.Readtext;
objstream.Close;
return(bytesToBSTR);
}%>
<body>
<%Response.Write(send_request("https://www.jb51.net/404.htm"))%>
</body>
</html>