JavaScript 크로스 도메인 요청 래핑 기능 및 사용 예

高洛峰
풀어 주다: 2016-12-07 16:57:42
원래의
1094명이 탐색했습니다.

이 기사의 예에서는 JavaScript 교차 도메인 요청 패키징 기능 및 사용법을 설명합니다. 참고하실 수 있도록 자세한 내용은 다음과 같습니다.

1. 소스코드

// 定义AJAX跨域请求的JSON
(function(){
  if(typeof window.$JSON== 'undefined'){
    window.$JSON= {};
  };
  $JSON._ajax = function(config){
    config = config[0] || {};
    this.url = config.url || '';
    this.type = config.type || 'xhr';
    this.method = (this.type == 'json') ? 'GET' : config.method.toUpperCase() || 'GET';
    this.param = config.param || null;
    this.callback = config.callback || {};
    this.XHR = null;
    if(typeof window._$JSON_callback == 'undefined'){
      window._$JSON_callback = {};
    }
    this._createRequest();
  };
  $JSON._ajax.prototype = {
    // 缓存XHR请求,再次再调用时不再进行判断
    _createXHR : function(){
      var methods = [
        function(){ return new XMLHttpRequest(); },
        function(){ return new ActiveXObject('Msxml2.XMLHTTP'); },
        function(){ return new ActiveXObject('Microsoft.XMLHTTP'); }
      ];
      for(var i = 0, l = methods.length; i < l; i++){
        try{
          methods[i]();
        }catch(e){
          continue;
        }
        this._createXHR = methods[i];
        return methods[i]();
      }
    },
    // 建立XHR请求
    _createRequest : function(){
      return (this.type == &#39;json&#39;) ? this._setJSONRequest() : this._setXHRRequest();
    },
    _setXHRRequest : function(){
      var _this = this;
      var param = &#39;&#39;;
      for(var i in this.param){
        if(param == &#39;&#39;){
          param = i+&#39;=&#39;+this.param[i];
        }else{
          param+= &#39;&&#39;+i+&#39;=&#39;+this.param[i];
        }
      }
      this.XHR = this._createXHR();
      this.XHR.onreadystatechange = function(){
        if(_this.XHR.readyState == 4 && _this.XHR.status == 200){
          _this.callback.success(_this.XHR.responseText);
        }else{
          _this.callback.failure(&#39;重新操作&#39;);
        }
      };
      this.XHR.open(this.method, this.url, true);
      this.XHR.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=utf-8");
      this.XHR.send(param);
    },
    // 建立JSON请求
    _setJSONRequest : function(){
      var head = document.getElementsByTagName(&#39;head&#39;)[0];
      var script = document.createElement(&#39;script&#39;);
      var fun = this._setRandomFun();
      var _this = this;
      var param = &#39;&#39;;
      for(var i in this.param){
        if(param == &#39;&#39;){
          param = i+&#39;=&#39;+this.param[i];
        }else{
          param+= &#39;&&#39;+i+&#39;=&#39;+this.param[i];
        }
      }
      script.type = &#39;text/javascript&#39;;
      script.charset = &#39;utf-8&#39;;
      if(head){
        head.appendChild(script);
      }else{
        document.body.appendChild(script);
      }
      // data:为回调函数所需要传入的参数
      // 定义页面中的回调函数,如例子中的"jsonpCallback()"方法
      window._$JSON_callback[fun.id] = function(data){
        _this.callback.success(data);
        setTimeout(function(){
          delete window._$JSON_callback[fun.id];
          script.parentNode.removeChild(script);
        }, 100);
      };
      script.src = this.url+&#39;?callback=&#39;+fun.name+&#39;&&#39;+param;
    },
    // 生成随机JSON回调函数
    _setRandomFun : function(){
      var id = &#39;&#39;;
      do{
        id = &#39;$JSON&#39;+Math.floor(Math.random()*10000);
      }while(window._$JSON_callback[id])
      return{
        id : id,
        name : &#39;window._$JSON_callback.&#39;+id
      }
    }
  };
  window.$JSON.ajax = function(){
    return new $JSON._ajax(arguments);
  }
})();
로그인 후 복사

2. 🎜>

//调用方式
var ajax = new $JSON.ajax({
  url : &#39;http://www.sina.com/api&#39;,
  type : &#39;json&#39;,
  method : &#39;get&#39;,
  param: {
    bar: true
  },
  callback : {
    success : function(data){
      console.log( &#39;55668&#39;,data);
    },
    failure : function(error){
      alert(errow);
    }
  }
});
로그인 후 복사


관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!