// 动态添加script获取里面的数据,,可实现跨域,不跨的当然也可以

 getFile:function(params){
try{
//创建script标签
var cbName=params.callback; //需要回调的函数
var head=document.getElementsByTagName('head')[0]; // 获取head标签
var script=document.createElement('script'); // 创建script标签
head.appendChild(script); // head中添加script标签
window.onload() = function(e){
head.removeChild(scriptTag); // 获得数据移除添加的script标签
if (e.type == 'error' || !responseData) {
// 返回错误信息或没有获取到信息
params.error&&params.error(e)
}else{
window[cbName]=null; // 清除回调
params.success&&params.success(responseData); // 回调success函数
}
}
window[cbName]=function(json){
responseData = json
};
params.url=params.url+"?callback="+cbName; // url中添加回调函数
script.src=params.url; // 给script标签添加url属性
}catch(e){
// 返回错误信息
params.error&&params.error(e)
}
} // 页面加载完后去获得city函数传入的数据
getFile({
url:"//***/city.json", //json文件、js文件、html都可以
callback:"city", // 跨域文件里调用的函数名
success:function(data){
console.log(data.name) // sunnie date得到的是一个对象
},error:function(e){
console.log(e)
}
}) city.json文件里的数据
city( {"name":"sunnie"} )
 (function(){
var Ajax=function(params){
this.config={
url:"",
type:"get",
async:true,
dataType:"json",
contentType:"application/x-www-form-urlencoded; charset=UTF-8",
data:{}
};
this.start(params);
};
var xhr = null;
Ajax.init=function(params){
new Ajax(params);
};
Ajax.prototype={
constructor: Ajax,
createXHR:function(){
if(typeof XMLHttpRequest!='undefined'){
return new XMLHttpRequest();
}else if(typeof ActiveXObject!='undefined'){
if(typeof arguments.callee.activeXString!='string'){
var versions=["MSXML2.XMLHttp.6.0","MSXML2.XMLHttp.3.0","MSXML2.XMLHttp"],i,len;
for(i=0,len=versions.length;i<len;i++){
try{
new ActiveXObject(versions[i]);
arguments.callee.activeXString=versions[i];
break;
}catch(ex){ }
}
}
return new ActiveXObject(arguments.callee.activeXString);
}else{
throw new Error("No XHR object available.");
}
},
start:function(params){
xhr=new this.createXHR();
if(params.url){
this.config.url=params.url;
}else{
throw new Error("url cannot be null!");
}
if(params.type){
this.config.type=params.type;
}
if(params.async){
this.config.async=params.async;
}
if(params.dataType){
this.config.dataType=params.dataType;
}
if(params.data){
this.config.data=params.data;
}
if(params.success){
this.config.success=params.success;
}
if(params.fail){
this.config.fail=params.fail;
}
if(params.beforeSend){
params.beforeSend();
} var complete=function(){
if(xhr.readyState==4){
if((xhr.status>=200&&xhr.status<300)||xhr.status==304){
if(params.success){
params.success(xhr.responseText);
}
}else{
if(params.fail){
params.fail();
}else{
throw new Error("Request was unsucessful:"+xhr.status);
}
}
}
} if(this.config.dataType=="json"||this.config.dataType=="JSON"){//非跨域
if((this.config.type=="GET")||(this.config.type=="get")){
for(var item in this.config.data){
this.config.url=addURLParam(this.config.url,item,this.config.data[item]);
}
xhr.onreadystatechange=complete;
xhr.open(this.config.type,this.config.url,this.config.async);
xhr.send(null);
}
if(this.config.type=="POST"||this.config.type=="post"){
xhr.addEventListener('readystatechange',complete);
xhr.open(this.config.type,this.config.url,this.config.async);
if(params.contentType){
this.config.contentType=params.contentType;
}
xhr.setRequestHeader("Content-Type",this.config.contentType);
xhr.send(serialize(this.config.data));
}
}else if((this.config.dataType=="jsonp")||(this.config.dataType=="JSONP")){//跨域
if((this.config.type=="GET")||(this.config.type=="get")){//jsonp只能进行get请求跨域
if(!params.url||!params.callback){
throw new Error("params is illegal!");
}else{
this.config.callback=params.callback;
}
//创建script标签
var cbName='callback';
var head=document.getElementsByTagName('head')[0];
this.config[this.config.callback]=cbName;
var scriptTag=document.createElement('script');
head.appendChild(scriptTag); //创建jsonp的回调函数
window[cbName]=function(json){
head.removeChild(scriptTag);
clearTimeout(scriptTag.timer);
window[cbName]=null;
params.success&&params.success(json);
};
//超时处理
if(params.time){
scriptTag.timer=setTimeout(function(){
head.removeChild(scriptTag);
params.fail&&params.fail({message:"over time"});
window[cbName]=null;
},params.time);
}
this.config.url=this.config.url+"?callback="+cbName;
for(var item in this.config.data){
this.config.url=addURLParam(this.config.url,item,this.config.data[item]);
}
scriptTag.src=this.config.url;
}
}else{
throw new Error("dataType is error!");
}
}
}
function addURLParam(url,name,value){
url+=(url.indexOf("?")==-1 ? "?" : "&");
url+=encodeURIComponent(name)+"="+encodeURIComponent(value);
return url;
}
//序列化函数
function serialize(data){
var val="";
var str="";
for(var item in data){
str=item+"="+data[item];
val+=str+'&';
}
return val.slice(0,val.length-1);
}
window["Ajax"]=Ajax;
})();
 window.onload=function(){
Ajax.init({
url:"http://localhost:8080/AjaxCROSTest/data.json",
type:"get",
dataType:"jsonp",
data:{"help":"me","to":"die"},
callback:"callback",
time:"1000",
beforeSend:function(){
//...
},
success:function(data){
//...
},
fail:function(ex){
console.log(ex);
}
});
}

自定义ajax的更多相关文章

  1. [jQuery]jQuery DataTables插件自定义Ajax分页实现

    前言 昨天在博客园的博问上帮一位园友解决了一个问题,我觉得有必要记录一下,万一有人也遇上了呢. 问题描述 园友是做前端的,产品经理要求他使用jQuery DataTables插件显示一个列表,要实现分 ...

  2. 自定义ajax,添加loading效果

    自定义ajax /** * @desc 自定义ajax请求,添加等待gif */ var n=0; $.defineAjax=function(obj){ n++; if(!$('#loadingDi ...

  3. EasyUI validatebox 自定义ajax验证用户名是否已存在

    <td><input type="text" id="userName" name="userName" class=&q ...

  4. 自定义ajax小工具以及使用

    function createXMLHttpRequest(){ try{ return new XMLHttpRequest(); }catch(e){ try{ return new Active ...

  5. 自定义ajax函数(仿照jQuery)

    AJAX介绍 AJAX = 异步 JavaScript 和 XML. 全称:Asynchronous Javascript And XML: AJAX 是一种用于创建快速动态网页的技术. 通过在后台与 ...

  6. 【Javascript】解决Ajax轮询造成的线程阻塞问题(过渡方案)

    一.背景 开发Web平台时,经常会需要定时向服务器轮询获取数据状态,并且通常不仅只开一个轮询,而是根据业务需要会产生数个轮询.这种情况下,性能低下的Ajax长轮询已经不能满足需求,频繁的访问还会造成线 ...

  7. jQuery 扩展 【ajax实例】

    先前写工具类都是自定义类,直接prototype,jQuery扩展这一块儿,一直也没写过,刚好今天有空,写个试试. 已经有很多人对jQuery,jQuery.fn,jQuery.fn.extend详细 ...

  8. [开源]jquery-ajax-cache:快速优化页面ajax请求,使用localStorage缓存请求

    项目:jquery-ajax-cache 地址:https://github.com/WQTeam/jquery-ajax-cache     最近在项目中用到了本地缓存localStorage做数据 ...

  9. Jquery 实现原理之 Ajax

    一:Jquery Ajax底层接口有:$.ajaxPrefilters.$.ajaxTransport.$.ajaxSettings.$ajaxSetup.$ajaxSettings; 其中$.aja ...

随机推荐

  1. centos 配置yum源

    1.yum配置 yum的配置文件在  /etc/yum.conf [root@mini ~]# cat /etc/yum.conf [main] cachedir=/var/cache/yum/$ba ...

  2. mybatis拓展框架对比

    对比项 mybatis-plus mybatis-enhance mapper fastmybatis 表名映射 @TableName @Table JPA:@Table JPA:@Table 主键映 ...

  3. Java基础—注解(转载)

    概念 注解(Annotation),也叫元数据.一种代码级别的说明.它是JDK1.5及以后版本引入的一个特性,与类.接口.枚举是在同一个层次.它可以声明在包.类.字段.方法.局部变量.方法参数等的前面 ...

  4. 登录plsql 报错 the account is locked --用户被锁

    登录数据库服务器,进入oracle用户下: [root@uumsnormal-oracle admin]# su - oracle [oracle@uumsnormal-oracle ~]$ sqlp ...

  5. DEPHI XE5 XE6 ANDROID IOS开发的几点体会

    DEPHI XE5 XE6 ANDROID IOS开发的几点体会 2014-09-04 20:48 1.不纠结于APK或者APP的大小.现在的客户端设备都很廉价,300元以上的新安卓设备都不在乎软件的 ...

  6. DataTable转换成IList

    //文章出处: http://www.cnblogs.com/hlxs/archive/2011/05/09/2087976.html DataTable转换成IList 在用C#作开发的时候经常要把 ...

  7. zookeeper 监听事件 CuratorWatcher

    zookeeper 监听事件 CuratorWatcher CuratorWatcher一次注册只监听一次,不监听查询. 1.监听测试类 package com.qy.learn.zk.curator ...

  8. Python3.x:常用基础语法

    Python3.x:常用基础语法 1,if else语句: 不执行if内的语句,需要用:pass if i>2: #跳过不执行 pass else: print("i= %s" ...

  9. Java-性能调优-理解GC日志

    [ ~]# cat gc.log.0 | grep 'Full GC' 1.652: [Full GC (System) 1.652: [CMS: 0K->21718K(262144K), 0. ...

  10. 20145313张雪纯 《Java程序设计》第7周学习总结

    20145313张雪纯 <Java程序设计>7周学习总结 教材学习内容总结 1967年定义的国际原子时,将秒的国际单位定义为铯原子辐射振动9192631170周耗费的时间. 为了简化日后对 ...