// 动态添加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. Elven Postman---hdu5444(二叉树)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5444  有一个序列,由这个序列可以画出一颗二叉树(每个节点的左边(W)都比它大,右边(E)都比它小), ...

  2. Design Patterns Example Code (in C++)

    Overview Design patterns are ways to reuse design solutions that other software developers have crea ...

  3. MySQL DBA的修炼与未来(参考篇)

    转自:https://blog.csdn.net/xielingshao/article/details/77840101 MySQL DBA的修炼与未来 随着MySQL地位爆炸式的提升, MySQL ...

  4. django cookie 提供的功能 参数

    # 用户发来数据带来所有COOKIES 这个cookie是字典 request.COOKIES # 获取字典 获取cookierequest.COOKIES["username111&quo ...

  5. 005-Shell echo命令

    一.概述 Shell 的 echo 指令,用于字符串的输出.命令格式: echo string 可以使用echo实现更复杂的输出格式控制. 1.显示普通字符串: echo "It is a ...

  6. 详解Spark sql用户自定义函数:UDF与UDAF

    UDAF = USER DEFINED AGGREGATION FUNCTION Spark sql提供了丰富的内置函数供猿友们使用,辣为何还要用户自定义函数呢?实际的业务场景可能很复杂,内置函数ho ...

  7. 1141 PAT Ranking of Institutions[难]

    1141 PAT Ranking of Institutions (25 分) After each PAT, the PAT Center will announce the ranking of ...

  8. Delphi APP 開發入門(八)SQLite資料庫

    Delphi APP 開發入門(八)SQLite資料庫 分享: Share on facebookShare on twitterShare on google_plusone_share   閲讀次 ...

  9. 3.MySQL必知必会之检索数据-SELECT语句

    本章将介绍如何使用SELECT语句从表中检索一个或多个数据列. 1.SELECT语句 SQL语句是由简单的英语单词构成的.这些单词称为关键字,每个SQL语句都是由一个或多个关键字构成的.大概,最经常使 ...

  10. Python-argparse-命令行与参数解析

    import argparse import numpy as np import cv2 import os import numpy.random as npr from dface.core.u ...