前段时间做毕设的时候,使用 PhoneGap打包web app的方式做开发,我使用的 PhoneGap版本比较老,没找到和服务器端通信的直接方法,因为html是在本地,所以使用标准的XHR是跨域的,当然也就不能用了,于是自己写了一可以跨域加载的小东东,使用动态 script 节点的方式,不是常见的jsonp的方式,因为写后台的老师比较土,AJAX都不知道,更不晓得让他每次我传递个函数名字过去,他包装数据了。就像YUI的 getScript函数一样,后台可以返回 var foo=2; 这样的数据,然后成功后,就可以利用 foo 这个全局变量了,写的过程中参考了 YUI和 jQuery 的实现方式,没有兼容其他浏览器,只兼容 Android。
代码如下,很简单,可能还有点小BUG,本来是打算接着完善的,但是现在好像没时间来折腾这个了,所以就先发上来,加上这段时间找 phoneGap找到我博客的人蛮多的,或许对大家有点帮助吧。
/**
* By Allen.M http://allenm.cn email: i@allenm.me 2010-05-22
* @method getScript
* url : string, the script's url;
* options: object (options)
* onSucess: function , it will be execute when the script load sucessful.
onFailure: function, it will be execute when the script load failure, the URL is wrong, OR the Internet problem .
onTimeout: function, it will be execute when the script is timeout.
erase: Boolean. The default value is true; if it's true, the script will be remove when the onload event fire.
timeout: number.(millisecond). The default value is 3000
charset: string. set the scirpt's charset. The default value is utf-8
*/
//function getData(url,onSuccess,onFailure,onTimeout,erase,timeout){
function getScript(url,options){
var script=document.createElement("script"), T, Now=+new Date(), timeout=options.timeout||3000, erase=options.erase||true,
head=document.getElementsByTagName("head")[0], isTimeout=false;
script.charset=options.charset||"utf-8";
if(url.indexOf('?')==-1){ // avoid the browser cache the data.
script.src=url+'?t='+(+new Date())+'&emp='+emp;
}else{
script.src=url+'&t='+(+new Date())+'&emp='+emp;
}
script.onload=function(){ // Handle the onload event
if(options.onSuccess&&(!isTimeout)){
options.onSuccess();
}
if(erase&&(!isTimeout)){
head.removeChild(script);
}
clearTimeout(T);
};
script.onerror = function(){ // Handle the onerror event
if(options.onFailure){
options.onFailure();
}
clearTimeout(T);
head.removeChild(script);
};
head.appendChild(script);
T = setTimeout (function(){ //Handle the timeout event
if(options.onTimeout){
options.onTimeout();
}
isTimeout=true;
head.removeChild(script);
},timeout);
}
比较简单,看看就懂了,我就不解释了,有什么意见和建议可以联系我,在 About Me 页面可以找到我的联系方式。

变量Now做何用的?
@Sway, 额,可以删去的,最开始的时候准备用来判断是否超时的,后来直接用来setTimeout