asp基于WebService 的天气预报ajax调用

 最近在做一个网站的时候,要用到天气预报,上baidu 搜了一下,提供这样的信息的很多,包括一些门户网站,QQ,sina,sohu等都有!但是有个缺点是他们好像是用<iframe>进行嵌入的,自定义形式很差,几乎不能改,而且还有广告(就是点击图标总是会跳转到相应的网站!)

于是,没有用,找了半天,发现有提供WebService的网站,也是在博客园上面看到别人提供的,今天就小用了一下!其实,asp 对我来说,也是用的很少的,现在还要用asp来调用webservice,没办法,baidu,google 吧!

还好有人早提供这样的代码,当然,能不能用还是要自己去尝试的,经过几番测试,发现,一下代码可行!

代码
<%@LANGUAGE="VBSCRIPT" CODEPAGE="65001"%>
<!--#include file="conn.asp" -->
<%
'session.CodePage=65001

datenow
=date
sql
="select top 1 * from t_weather"
set rs=server.CreateObject("Adodb.recordset")
rs.open sql,conn,
1,1
if not rs.eof and not rs.bof then

if rs("remark")<>cstr(datenow) then
//response.Write("不等")
//response.Write(rs("remark"))
url
="http://www.webxml.com.cn/WebServices/WeatherWebService.asmx"
SoapRequest
="<?xml version="&chr(34)&"1.0"&chr(34)&" encoding="&chr(34)&"utf-8"&chr(34)&"?>"& _
"<soap:Envelope xmlns:xsi="&CHR(34)&"http://www.w3.org/2001/XMLSchema-instance"&CHR(34)&" "& _
"xmlns:xsd="&CHR(34)&"http://www.w3.org/2001/XMLSchema"&CHR(34)&" "& _
"xmlns:soap="&CHR(34)&"http://schemas.xmlsoap.org/soap/envelope/"&CHR(34)&">"& _
"<soap:Body>"& _
"<getWeatherbyCityName xmlns="&CHR(34)&"http://WebXml.com.cn/"&CHR(34)&">"& _
"<theCityName>58357</theCityName>"& _
"</getWeatherbyCityName>"& _
"</soap:Body>"& _
"</soap:Envelope>"
Set xmlDOC =Server.CreateObject("MSXML.DOMDocument")
Set xmlhttp = server.CreateObject("Msxml2.XMLHTTP")
xmlhttp.Open
"POST",url,false
xmlhttp.setRequestHeader
"HOST","www.webxml.com.cn"
xmlhttp.setRequestHeader
"Content-Type", "text/xml;charset=utf-8"
xmlhttp.setRequestHeader
"Content-Length",LEN(SoapRequest)
'一定要与WEBSERVICE的命名空间相同,否则服务会拒绝
xmlhttp.setRequestHeader "SOAPAction", "http://WebXml.com.cn/getWeatherbyCityName"

xmlhttp.Send(SoapRequest)
'这样就利用XMLHTTP成功发送了与SOAP示例所符的SOAP请求.
'
检测一下是否成功:
'
Response.Write xmlhttp.Status&"&nbsp;"
'
Response.Write xmlhttp.StatusText
'
Response.Write xmlhttp.responseText

bOK
= xmlDOC.load(xmlhttp.responseXML)
xmlStr
= xmlDOC.xml

sql2
="select * from t_weather where id="&rs("id")
set rs2=server.CreateObject("Adodb.recordset")
rs2.open sql2,conn,
3,2
if not rs.eof then
rs2(
"weather")=xmlStr
rs2(
"remark")=datenoe
rs2.update
end if
rs2.close
set rs2=nothing
response.Write(xmlStr)
else
response.Write(
cstr(rs("weather")))
end if
else
url
="http://www.webxml.com.cn/WebServices/WeatherWebService.asmx"
SoapRequest
="<?xml version="&chr(34)&"1.0"&chr(34)&" encoding="&chr(34)&"utf-8"&chr(34)&"?>"& _
"<soap:Envelope xmlns:xsi="&CHR(34)&"http://www.w3.org/2001/XMLSchema-instance"&CHR(34)&" "& _
"xmlns:xsd="&CHR(34)&"http://www.w3.org/2001/XMLSchema"&CHR(34)&" "& _
"xmlns:soap="&CHR(34)&"http://schemas.xmlsoap.org/soap/envelope/"&CHR(34)&">"& _
"<soap:Body>"& _
"<getWeatherbyCityName xmlns="&CHR(34)&"http://WebXml.com.cn/"&CHR(34)&">"& _
"<theCityName>58357</theCityName>"& _
"</getWeatherbyCityName>"& _
"</soap:Body>"& _
"</soap:Envelope>"
Set xmlDOC =Server.CreateObject("MSXML.DOMDocument")
Set xmlhttp = server.CreateObject("Msxml2.XMLHTTP")
xmlhttp.Open
"POST",url,false
xmlhttp.setRequestHeader
"HOST","www.webxml.com.cn"
xmlhttp.setRequestHeader
"Content-Type", "text/xml;charset=utf-8"
xmlhttp.setRequestHeader
"Content-Length",LEN(SoapRequest)
'一定要与WEBSERVICE的命名空间相同,否则服务会拒绝
xmlhttp.setRequestHeader "SOAPAction", "http://WebXml.com.cn/getWeatherbyCityName"

xmlhttp.Send(SoapRequest)
'这样就利用XMLHTTP成功发送了与SOAP示例所符的SOAP请求.
'
检测一下是否成功:
'
Response.Write xmlhttp.Status&"&nbsp;"
'
Response.Write xmlhttp.StatusText
'
Response.Write xmlhttp.responseText

bOK
= xmlDOC.load(xmlhttp.responseXML)
xmlStr
= xmlDOC.xml
rs.close
sql
="select * from t_weather where (id is null)"
'sql="insert into t_weather (weather,remark) values ('"&cstr(xmlStr)&"','"&datenow&"')"
rs.open sql,conn,3,2
rs.addnew
rs(
"weather")=cstr(xmlStr)
rs(
"remark")=cstr(datenow)
rs.update

end if

rs.close
set rs=nothing
conn.close
set conn=nothing
%
>

本来是Asp 的代码,没找到asp的语法高亮就用了vb.net!

上面代码可能有点乱,主要是我改过了,主要是不想反复调用Webservice,天气预报嘛!一天调用一次就可以了!以后就从数据库调用了!这个有个问题,折腾了我很久,就是asp的编码问题,因为提供Webservice的服务的得到的是utf-8的xml信息,一开始,我这个页面的编码是gb2312的,所以显示xml信息的时候,总是会出错,提示说什么xml文件内容有错误,就是打不开了!后来,也是折腾了好久,才知道把编码改过utf-8的就OKle!

即最上面的那句话“<%@LANGUAGE="VBSCRIPT" CODEPAGE="65001"%>”

其实里面主要调用WebService的内容就是下面的代码了

<% 
url="http://www.webxml.com.cn/WebServices/WeatherWebService.asmx"
        SoapRequest="<?xml version="&chr(34)&"1.0"&chr(34)&" encoding="&chr(34)&"utf-8"&chr(34)&"?>"& _
        "<soap:Envelope xmlns:xsi="&CHR(34)&"http://www.w3.org/2001/XMLSchema-instance"&CHR(34)&" "& _ 
        "xmlns:xsd="&CHR(34)&"http://www.w3.org/2001/XMLSchema"&CHR(34)&" "& _   
        "xmlns:soap="&CHR(34)&"http://schemas.xmlsoap.org/soap/envelope/"&CHR(34)&">"& _   
        "<soap:Body>"& _ 
        "<getWeatherbyCityName xmlns="&CHR(34)&"http://WebXml.com.cn/"&CHR(34)&">"& _   
    "<theCityName>58357</theCityName>"& _   
    "</getWeatherbyCityName>"& _   
    "</soap:Body>"& _   
    "</soap:Envelope>"   
    Set xmlDOC =Server.CreateObject("MSXML.DOMDocument")   
Set xmlhttp = server.CreateObject("Msxml2.XMLHTTP")   
xmlhttp.Open "POST",url,false 
xmlhttp.setRequestHeader "HOST","www.webxml.com.cn"   
xmlhttp.setRequestHeader "Content-Type", "text/xml;charset=utf-8"   
xmlhttp.setRequestHeader "Content-Length",LEN(SoapRequest)   
'一定要与WEBSERVICE的命名空间相同,否则服务会拒绝   
xmlhttp.setRequestHeader "SOAPAction", "http://WebXml.com.cn/getWeatherbyCityName"    
  
xmlhttp.Send(SoapRequest)   
'这样就利用XMLHTTP成功发送了与SOAP示例所符的SOAP请求.   
'检测一下是否成功:   
'Response.Write xmlhttp.Status&" "   
'Response.Write xmlhttp.StatusText   
'Response.Write xmlhttp.responseText   
  
bOK = xmlDOC.load(xmlhttp.responseXML)   
xmlStr = xmlDOC.xml

response.write(xmlStr)
%>

记录一下,以后就可以找了!

最下面的就是用ajax 调用此页面输出的xml信息了,主要就是天气情况了,

// JavaScript Document
function createXMLDom(){
    if (window.ActiveXObject) 
        var xmldoc = new ActiveXObject("Microsoft.XMLDOM");
    else 
        if (document.implementation && document.implementation.createDocument) 
            var xmldoc = document.implementation.createDocument("", "", null);
    xmldoc.async = false;
    //为了和FireFox一至,这里不能改为False;
    xmldoc.preserveWhiteSpace = true;
    return xmldoc;
}

function createXMLHttp(){
    var xmlHttp;
    if (window.ActiveXObject) {
        xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else {
        xmlHttp = new XMLHttpRequest();
    }
    return xmlHttp;
}

//加载XML文件。
function getXML(xmlFile){
    var xmlDom = createXMLDom();
    try {
        xmlDom.load(xmlFile);
    } 
    catch (e) {
        var xmlHttp = createXMLHttp();
        xmlHttp.onreadystatechange = function(){
            if (xmlHttp.readyState == 4) {
                xmlDom = xmlHttp.responseXML;
            }
            else {
                window.state = "XML文件加载中...";
            }
        }
        xmlHttp.open("GET", xmlFile, false);
        xmlHttp.send(null);
    }
    return xmlDom.documentElement;
}

//取出指定节点的属性。
function getDOMAtt(pNode, pAttribute){
    try {
        return pNode.attributes.getNamedItem(pAttribute).nodeValue;
    } 
    catch (e) {
        //alert("指定节点不存在,或指定属性:"+pAttribute+" 不存在!")
        return false;
    }
    
}

//获取当前节点的属性列表
function attList(pNode){
    if (pNode.nodeType == 4) 
        return '';
    var oAtt, tmpString = "[ ";
    try {
        for (var i = 0; oAtt = pNode.attributes[i]; i++) {
            tmpString += oAtt.nodeName + " = '" + oAtt.nodeValue + "' ";
        }
        tmpString += " ]"
        return tmpString;
    } 
    catch (e) {
        return ''
    }
}

//获取节点名称
function getNodeName(pNode){
    if (pNode.nodeType == 4) 
        return '';
    return pNode.nodeName;
}
//获取节点名称
function getNodeValue(pNode){
    try {
        return " : " + pNode.firstChild.nodeValue;
    } 
    catch (e) {
        return ''
    }
}

//<----------------------------调试功能函数------------------------------>
//输出空格
function nbsp(pNum){
    var tmpString = ""
    for (var i = 0; i < pNum; i++) {
        tmpString += " "//这里是全角的空格
    }
    return tmpString;
}

//用于高度输出完整的XML树
var j=0;
function switchTree( pNode, pLevel ){
	j=j+1;
    var tNode, i;
    for (i = 0; tNode = pNode.childNodes[i]; i++) {
        if (tNode.nodeType == 3) 
            continue;//因为preserveWhiteSpace等于true
        document.write(nbsp(pLevel),"<b>[",i,"][",j,"]</b><font color='blue'><b>"+getNodeName(tNode)+"</b></font><font color='red'>"+attList(tNode)+"</font>",getNodeValue(tNode),"<br />");
        
        switchTree(tNode, pLevel + 1);
    }
}
function output(pNode,i){
		var tnode;
		tnode=pNode.getElementsByTagNames("string");
		
		documnet.write(tnode.length);
	}


一开始用的上面getxml 代码,发现只能在IE下可以用,firefox 下不行!

于是就要分别对待了,下面是最后的结合上面的js代码和jquery框架来实现!

weather.js

var Sys = {};
        var ua = navigator.userAgent.toLowerCase();
        if (window.ActiveXObject)
            Sys.ie = ua.match(/msie ([\d.]+)/)[1]
        else if (document.getBoxObjectFor)
            Sys.firefox = ua.match(/firefox\/([\d.]+)/)[1]
        else if (window.MessageEvent && !document.getBoxObjectFor)
            Sys.chrome = ua.match(/chrome\/([\d.]+)/)[1]
        else if (window.opera)
            Sys.opera = ua.match(/opera.([\d.]+)/)[1]
        else if (window.openDatabase)
            Sys.safari = ua.match(/version\/([\d.]+)/)[1];
	
	function showweather(){
	
	jQuery.ajax({
		   url:"weather.asp",cache:false,success:function(tt){
			   //	var patrn="/\d+/g";
				//document.write(tt);
			  //alert(tt.replace("\n","")+"<br/>");
			  var ttstr=jQuery(tt).find("string").eq(5).text();
			  
			  var ttstr2=jQuery(tt).find("string").eq(6).text();
			  var ttstr8=jQuery(tt).find("string").eq(8).text();
			  var ttstr9=jQuery(tt).find("string").eq(9).text();
			  var simg="<img src='/pic/weather/"+ttstr8+"' /><img src='/pic/weather/"+ttstr9+"' />";
			  jQuery("#w_img").html(simg);
			  wt=ttstr2.split("日");
			jQuery("#Weather").html(wt[1]+ttstr);
			//alert(jQuery("#Weather").html());
		   }
		   })
	}
	///url:"weather.asp",data:"command=user&code=",cache:false,success:function(html){
		
		function ieweather(){
				
		var Domroot=getXML("weather.asp");
		var tt=Domroot.getElementsByTagName("string");
		//for(var i=0;i<tt.length;i++){
			wt=tt[6].text.split("日");
			var str=wt[1]+tt[5].text;
			var simg="<img src='/pic/weather/"+tt[8].text+"' /><img src='/pic/weather/"+tt[9].text+"' />";
			//alert(str);
			jQuery("#w_img").html(simg);
			jQuery("#Weather").html(str);
		//}
		//alert(tt.length);
		}
		
		jQuery(function(){
			   if(Sys.firefox){
			   	showweather();
			   }
			   else{
				ieweather();
			   }
			   })

最上面的代码是用来却别浏览器的,然后是分别对ie和firefox 作了却别对待!其中ie用的是上面的getxml函数,而firefox则是用jquery中的ajax功能函数!

最后,截图如下!

posted @ 2010-12-16 21:21  neve  阅读(1043)  评论(0编辑  收藏  举报