// 动态添加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. 使用arc进行code review

    https://secure.phabricator.com/book/phabricator/article/arcanist_quick_start/ 使用流程: 流程 本部分来自arcanist ...

  2. Win32调试API原理

    在Win32中自带了一些API函数,它们提供了相当于一般调试器的大多数功能,这些函数统称为Win32调试API(Win32 Debug API).利用这些API可以做到加载一个程序或捆绑到一个正在运行 ...

  3. javaScript 调用构造函数 Array() 时没有使用参数, length总是0

    如果调用构造函数 Array() 时没有使用参数,那么返回的数组为空,length 字段为 0. 当调用构造函数时只传递给它一个数字参数,该构造函数将返回具有指定个数.元素为 undefined 的数 ...

  4. nodejs实战《一起学 Node.js》 使用 Express + MongoDB 搭建多人博客

    GitHub: https://github.com/nswbmw/N-blog N-blog 使用 Express + MongoDB 搭建多人博客 开发环境 Node.js: 6.9.1 Mong ...

  5. java 字符串截取的方法

    1.split()+正则表达式来进行截取. 将正则传入split().返回的是一个字符串数组类型.不过通过这种方式截取会有很大的性能损耗,因为分析正则非常耗时. String str = " ...

  6. python爬虫中文乱码解决方法

    python爬虫中文乱码 前几天用python来爬取全国行政区划编码的时候,遇到了中文乱码的问题,折腾了一会儿,才解决.现特记录一下,方便以后查看. 我是用python的requests和bs4库来实 ...

  7. H5移动端的一些坑、、、

    H5项目常见问题及注意事项 Meta基础知识: H5页面窗口自动调整到设备宽度,并禁止用户缩放页面 //一.HTML页面结构 <meta name="viewport" co ...

  8. 手把手教 GitHub + Hexo 搭建博客

    前言 在很久以前,博主就想着要有自主的博客专栏或者网站.经历了博客园这个需要所谓的编辑审核,一直比较困惑,这些编辑是什么出身,怎么知道技术博客的价值性. 接下来找到了开源中国,这个可以自由发言的地方. ...

  9. Vim 我用的python相关插件

    1. pydoc.vim(https://github.com/vim-scripts/pydoc.vim)  查找python文档. 使用方法: :Pydoc <keyword>     ...

  10. 一步一步学EF系列四【升级篇 实体与数据库的映射】

    之前的三张为基础篇,如果不考虑架构问题,做一般的小程序,以足够用了.基本的增删改查也都有了.但是作为学习显然是不够的.通过之前三章的学习,有没有发现这样写有什么问题,有没有觉得繁琐的?可能有人会说,之 ...