1 // 动态添加script获取里面的数据,,可实现跨域,不跨的当然也可以
2
3 getFile:function(params){
4 try{
5 //创建script标签
6 var cbName=params.callback; //需要回调的函数
7 var head=document.getElementsByTagName('head')[0]; // 获取head标签
8 var script=document.createElement('script'); // 创建script标签
9 head.appendChild(script); // head中添加script标签
10 window.onload() = function(e){
11 head.removeChild(scriptTag); // 获得数据移除添加的script标签
12 if (e.type == 'error' || !responseData) {
13 // 返回错误信息或没有获取到信息
14 params.error&¶ms.error(e)
15 }else{
16 window[cbName]=null; // 清除回调
17 params.success&¶ms.success(responseData); // 回调success函数
18 }
19 }
20 window[cbName]=function(json){
21 responseData = json
22 };
23 params.url=params.url+"?callback="+cbName; // url中添加回调函数
24 script.src=params.url; // 给script标签添加url属性
25 }catch(e){
26 // 返回错误信息
27 params.error&¶ms.error(e)
28 }
29 }
30
31
32
33 // 页面加载完后去获得city函数传入的数据
34 getFile({
35 url:"//***/city.json", //json文件、js文件、html都可以
36 callback:"city", // 跨域文件里调用的函数名
37 success:function(data){
38 console.log(data.name) // sunnie date得到的是一个对象
39 },error:function(e){
40 console.log(e)
41 }
42 })
43
44
45 city.json文件里的数据
46 city( {"name":"sunnie"} )
1 (function(){
2 var Ajax=function(params){
3 this.config={
4 url:"",
5 type:"get",
6 async:true,
7 dataType:"json",
8 contentType:"application/x-www-form-urlencoded; charset=UTF-8",
9 data:{}
10 };
11 this.start(params);
12 };
13 var xhr = null;
14 Ajax.init=function(params){
15 new Ajax(params);
16 };
17 Ajax.prototype={
18 constructor: Ajax,
19 createXHR:function(){
20 if(typeof XMLHttpRequest!='undefined'){
21 return new XMLHttpRequest();
22 }else if(typeof ActiveXObject!='undefined'){
23 if(typeof arguments.callee.activeXString!='string'){
24 var versions=["MSXML2.XMLHttp.6.0","MSXML2.XMLHttp.3.0","MSXML2.XMLHttp"],i,len;
25 for(i=0,len=versions.length;i<len;i++){
26 try{
27 new ActiveXObject(versions[i]);
28 arguments.callee.activeXString=versions[i];
29 break;
30 }catch(ex){
31
32 }
33 }
34 }
35 return new ActiveXObject(arguments.callee.activeXString);
36 }else{
37 throw new Error("No XHR object available.");
38 }
39 },
40 start:function(params){
41 xhr=new this.createXHR();
42 if(params.url){
43 this.config.url=params.url;
44 }else{
45 throw new Error("url cannot be null!");
46 }
47 if(params.type){
48 this.config.type=params.type;
49 }
50 if(params.async){
51 this.config.async=params.async;
52 }
53 if(params.dataType){
54 this.config.dataType=params.dataType;
55 }
56 if(params.data){
57 this.config.data=params.data;
58 }
59 if(params.success){
60 this.config.success=params.success;
61 }
62 if(params.fail){
63 this.config.fail=params.fail;
64 }
65 if(params.beforeSend){
66 params.beforeSend();
67 }
68
69 var complete=function(){
70 if(xhr.readyState==4){
71 if((xhr.status>=200&&xhr.status<300)||xhr.status==304){
72 if(params.success){
73 params.success(xhr.responseText);
74 }
75 }else{
76 if(params.fail){
77 params.fail();
78 }else{
79 throw new Error("Request was unsucessful:"+xhr.status);
80 }
81 }
82 }
83 }
84
85 if(this.config.dataType=="json"||this.config.dataType=="JSON"){//非跨域
86 if((this.config.type=="GET")||(this.config.type=="get")){
87 for(var item in this.config.data){
88 this.config.url=addURLParam(this.config.url,item,this.config.data[item]);
89 }
90 xhr.onreadystatechange=complete;
91 xhr.open(this.config.type,this.config.url,this.config.async);
92 xhr.send(null);
93 }
94 if(this.config.type=="POST"||this.config.type=="post"){
95 xhr.addEventListener('readystatechange',complete);
96 xhr.open(this.config.type,this.config.url,this.config.async);
97 if(params.contentType){
98 this.config.contentType=params.contentType;
99 }
100 xhr.setRequestHeader("Content-Type",this.config.contentType);
101 xhr.send(serialize(this.config.data));
102 }
103 }else if((this.config.dataType=="jsonp")||(this.config.dataType=="JSONP")){//跨域
104 if((this.config.type=="GET")||(this.config.type=="get")){//jsonp只能进行get请求跨域
105 if(!params.url||!params.callback){
106 throw new Error("params is illegal!");
107 }else{
108 this.config.callback=params.callback;
109 }
110 //创建script标签
111 var cbName='callback';
112 var head=document.getElementsByTagName('head')[0];
113 this.config[this.config.callback]=cbName;
114 var scriptTag=document.createElement('script');
115 head.appendChild(scriptTag);
116
117 //创建jsonp的回调函数
118 window[cbName]=function(json){
119 head.removeChild(scriptTag);
120 clearTimeout(scriptTag.timer);
121 window[cbName]=null;
122 params.success&¶ms.success(json);
123 };
124 //超时处理
125 if(params.time){
126 scriptTag.timer=setTimeout(function(){
127 head.removeChild(scriptTag);
128 params.fail&¶ms.fail({message:"over time"});
129 window[cbName]=null;
130 },params.time);
131 }
132 this.config.url=this.config.url+"?callback="+cbName;
133 for(var item in this.config.data){
134 this.config.url=addURLParam(this.config.url,item,this.config.data[item]);
135 }
136 scriptTag.src=this.config.url;
137 }
138 }else{
139 throw new Error("dataType is error!");
140 }
141 }
142 }
143 function addURLParam(url,name,value){
144 url+=(url.indexOf("?")==-1 ? "?" : "&");
145 url+=encodeURIComponent(name)+"="+encodeURIComponent(value);
146 return url;
147 }
148 //序列化函数
149 function serialize(data){
150 var val="";
151 var str="";
152 for(var item in data){
153 str=item+"="+data[item];
154 val+=str+'&';
155 }
156 return val.slice(0,val.length-1);
157 }
158 window["Ajax"]=Ajax;
159 })();
1 window.onload=function(){
2 Ajax.init({
3 url:"http://localhost:8080/AjaxCROSTest/data.json",
4 type:"get",
5 dataType:"jsonp",
6 data:{"help":"me","to":"die"},
7 callback:"callback",
8 time:"1000",
9 beforeSend:function(){
10 //...
11 },
12 success:function(data){
13 //...
14 },
15 fail:function(ex){
16 console.log(ex);
17 }
18 });
19 }