要解决ajax跨域问题,网上给出的方法有二:
1是构建服务器端的代理。简而言之,就是ajax中调用的实质还是本机的url,而服务器端替js去取回远端地址。
2.利用script标记,生成一个 <script src="...." type="text/javascript"></script> 标签。在js加载完成后,再执行后续操作。
就是将原来新建xmlHTTPrequest对象的操作改成了新建script标签的操作.
这里给出一个例子:
#ajah.js
var
Ajah
=
function
(url,varname,handleSuccess,handleFailure)
...
{
/**//**
* handleSuccess,handleFailure must be functions
* */
script = document.createElement("script");
script.src=url;
var handler = function(str)
...{
handleSuccess(str);
}
script.onload = function()
...{
var json=eval(varname);
handler(json);
}
if(window.ie)
...{
script.onreadystatechange = function()
...{
if(script.readyState=='complete'||script.readyState== 'loaded')
...{
var json=eval(varname);
if(typeof json != 'undefined')
...{
handler(json);
}
}
}
}
document.body.appendChild(script);
}
/**//**
* handleSuccess,handleFailure must be functions
* */
script = document.createElement("script");
script.src=url;
var handler = function(str)
...{
handleSuccess(str);
}
script.onload = function()
...{
var json=eval(varname);
handler(json);
}
if(window.ie)
...{
script.onreadystatechange = function()
...{
if(script.readyState=='complete'||script.readyState== 'loaded')
...{
var json=eval(varname);
if(typeof json != 'undefined')
...{
handler(json);
}
}
}
}
document.body.appendChild(script);
}
而在网页中应这样调用:
#demo.html
<
pre
>
<! DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN" >
< html >
< head >
< meta name ="generator" content =
"HTML Tidy for Linux (vers 1 September 2005), see www.w3.org" >
< title ></ title >
< script src ="mootools.js" ></ script >
< script src ="ajah.js" ></ script >
</ head >
< body >
< script > ...
var ajah=new Ajah("data.js","json198",function(str)...{
console.debug("returned:");
console.debug(str);
},
function(str)...{});
</ script >
</ body >
</ html >
</ pre >
<! DOCTYPE html PUBLIC "-//W3C//DTD HTML 3.2//EN" >
< html >
< head >
< meta name ="generator" content =
"HTML Tidy for Linux (vers 1 September 2005), see www.w3.org" >
< title ></ title >
< script src ="mootools.js" ></ script >
< script src ="ajah.js" ></ script >
</ head >
< body >
< script > ...
var ajah=new Ajah("data.js","json198",function(str)...{
console.debug("returned:");
console.debug(str);
},
function(str)...{});
</ script >
</ body >
</ html >
</ pre >
被调用的数据文件如下
#data.js
var
json198
=
"
hello,this is json198
"
;
funciton Ajah(url,varname,handleSuccess,handleFailure){…}
Ajah这个构造函数调用四个参数:
url:远端地址
varname:远端返回数据的变量名
handleSuccess:加载完毕后加载的函数
handleFailure:暂时没用上