AJAX的封装和JSONP

2016-10-10  本文已影响356人  Simon_s

1、封装AJAX

// 1、浏览器适配
// 2、传入参数:请求方式、请求接口地址、请求参数、请求成功的回调函数、请求失败的回调函数

function ajaxFun (method, url, data, successFun, failFun) {
// 1、根据浏览器的支持情况创建XMLHttpRequest对象
var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
    // 2、判断请求方式的类型
// 把method转换为大写:toUpperCase:先把变量中的字符串拷贝一份出来,然后针对拷贝的那一份修改为大写
//   console.log( method.toUpperCase() );

var upperMethod = method.toUpperCase();

if (upperMethod == 'GET') {
    // 2.1、请求为get请求时,配置请求参数,并发送请求
    xhr.open(upperMethod, url+'?'+data, true);
    xhr.send(null);
    
} else if (upperMethod == 'POST') {
    // 2.2、请求为post请求,配置请求参数,并发送请求
    xhr.open(upperMethod, url, true);
    xhr.send(data);
    
} else {
    // 如果传入的请求方式并不是get或post,则弹出错误提示,并关闭函数的执行
//      alert('你的请求方式传错啦!');
    console.error('请求参数错误,必须是get或post的一种');
    return;
}

// 3、监听服务器响应,根据服务器传回来的信息调用不同的回调函数
xhr.onreadystatechange = function () {
    if (xhr.readyState == 4 && xhr.status == 200) {
        successFun(xhr.responseText);
    } else if (xhr.readyState == 4)  {
        
        failFun('请求失败');
        console.error(xhr.status);
    }
    
}

}

2、打破同源限制

// 同源:当两个接口的协议、域名、端口号都相等时,这俩接口是同源的,只要有一个条
件不相等,则非同源。不是同源的两个页面不能互相访问本地缓存、不能互相修改dom节点、不能使用ajax请求对方接口数据
        
        
        // 跨域请求数据
        
        // http://wthrcdn.etouch.cn/weather_mini?city=北京
        
        // 1、创建xmlhttprequest对象
//          var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new 
ActiveXObject('Microsoft.XMLHTTP');
//          // 2、配置请求参数
//          xhr.open('GET', 'http://wthrcdn.etouch.cn/weather_mini?city=北京', true);
//          //3、发送请求
//          xhr.send(null);
//          // 4、监听服务器返回数据
//          xhr.onreadystatechange = function () {
//              if (xhr.readyState == 4 && xhr.status == 200) {
//                  alert(xhr.responseText);
//              }
//          }


// JSONP:利用scritp标签请求外部服务器中的数据,从而绕开同源策略对AJAX请求数据的限制。
    
//      var script = document.createElement('script');
//      script.type = 'text/javascript';
//      script.src = 'http://10.0.159.198/data.php?callback=foo';
//      document.getElementsByTagName('head')[0].appendChild(script);
//      
//      
//      
//      function foo (data) {
//          alert(data.great);
//          
//          
//      }

3、 封装jsonp

   jsonp的本质:利用script标签中src属性可以加载任意文件的特性,通过这个属性来访
问数据接口(添加一个回调函数作为参数),而数据接口会返回一个由回调函数名包裹的json数据,从而达到获取跨域数据的目的。
    
    // 把创建script标签的步骤封装在一个函数中:
//      function creatScriptTag (srcString) {
//          var script = document.createElement('script');
//          script.type = 'text/javascript';
//          script.src = srcString;
//          document.getElementsByTagName('head')[0].appendChild(script);
//      }
//      
//      creatScriptTag('http://10.0.159.198/data.php?callback=abc');
//      
//      function abc (data) {
//          alert(data);
//      }
上一篇下一篇

猜你喜欢

热点阅读