成功实现ajax,xmlhttp跨域访问

其实这篇文章是那篇YAHOO!天气预报的后续,因为天气预报是利用XMLHTTP实现的,而XMLHTTP存在跨域访问的问题,在还没本篇文章之前,我直接通过静态的javascript来获取数据,在本机测试是正常的,但是放到服务器上就不行了,提示没有访问权限,百度了一下,原来已经有好多人遇到了这问题—–XMLHTTP跨域访问.不过以前我用ASP在服务器上是可以实现数据获取的,于是我就想是不是可以先利用ASP获取到数据,然后再用javascript获取ASP收到的数据呢,我试验了一下,结果是可行的. [smile] !~

好高兴,这个天气预报终于是圆满的解决了.

附代码:
weather.asp页

<%
p = “http://weather.cn.yahoo.com/weather.html?city=%E7%83%9F%E5%8F%B0”
Response.BinaryWrite ZQcnGet(p)
Response.Flush

Function ZQcnGet(url)
Set Retrieval = CreateObject(“Microsoft.XMLHTTP”)
With Retrieval
.Open “Get”, url, False, “”, “”
.Send
ZQcnGet = .ResponseBody
End With
Set Retrieval = Nothing
End Function
%>

weather.js页面

// JavaScript Document
/*
================
Yahoo!天气预报
Jena.want [迦楠]
http://www.ishere.cn [在这里,迦楠的BLOG]
Last Edit:2007.01.15 解决跨域访问的问题.
================
*/
var cDOMtype = ”;
if (document.getElementById)
{
cDOMtype = “std”;
}
else if (document.all)
{
cDOMtype = “ie4”;
}
else if (document.layers)
{
cDOMtype = “ns4”;
}

// #############################################
// function to emulate document.getElementById
function _$$(idname){
return fetch_object(idname);
}
function fetch_object(idname)
{
switch (cDOMtype)
{
case “std”:
{
return document.getElementById(idname);
}
break;

case “ie4”:
{
return document.all[idname];
}
break;

case “ns4”:
{
return document.layers[idname];
}
break;
}
}

function get_weather(){
if(_$$(‘weatherook2’)){
_$$(‘weatherook2’).innerHTML = “<marquee behavior=”slide”>The data is loading…</marquee>”;

var xml;
if (window.XMLHttpRequest) {
xml=new XMLHttpRequest();
}else if (window.ActiveXObject){
xml=new ActiveXObject(“Microsoft.XMLHTTP”);
}

xml.onreadystatechange = function(){
if(xml.readyState == 4){
if ( xml.status == 200 || xml.status == 304 ){
_$$(‘weatherook2′).innerHTML = get_content(xml.responseText,'<div class=”dt_d”>’,'<div class=”l2″>’);
}
}

}

xml.open(“GET” , uPath + “weather.asp” ,false);
xml.setRequestHeader(“If-Modified-Since”,”Tus, 9 Jan 2007 09:17:54 GMT”);
xml.send(“”);
}else{
alert(‘invalid page id’);
}
}
function get_content(str,starM1,starM2){
var starP,endP;
if(str){
starP = str.indexOf(starM1);
endP = str.indexOf(starM2)-1;
}
return str.substring(starP,endP);
}

window.onload = get_weather ;

weather.html页

<!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=utf-8″ />
<title>无标题文档</title>
<link href=”weather.css” rel=”stylesheet” type=”text/css” media=”screen” />
<script language=”javascript”>
var uPath = ”;
</script>
<script language=”javascript” src=”weather.js”></script>
</head>

<body>
<h3>YAHOO!天气预报</h3>
<div style=”width:130px”><div id=”weatherook2″ class=”map_cnt2″></div></div>
</body>
</html>

Leave a Comment

Your email address will not be published.

*