Home Web Front-end JS Tutorial Detailed explanation of custom ajax support for cross-domain component encapsulation

Detailed explanation of custom ajax support for cross-domain component encapsulation

Feb 09, 2018 am 09:49 AM
ajax encapsulation customize

This article mainly gives you a detailed analysis of the knowledge points related to custom ajax support for cross-domain component encapsulation. Friends who are interested in this can refer to it and hope to help everyone.

Class.create() analysis

Imitate prototype to create class inheritance

var Class = {
  create: function () {
    var c = function () {
      this.request.apply(this, arguments);
    }
    for (var i = 0, il = arguments.length, it; i < il; i++) {
      it = arguments[i];
      if (it == null) continue;
      Object.extend(c.prototype, it);
    }
    return c;
  }
};
Object.extend = function (tObj, sObj) { 
  for (var o in sObj) {
    tObj[o] = sObj[o];
  }
  return tObj;
};
Copy after login

ajax definition: ZIP_Ajax=Class.create();

The create method returns a constructor request, which is equivalent to var ZIP_Ajax= function(){ this.request.apply(this, arguments); }; executed inside the function by impersonating the object. The process of a construction is equivalent to handing over the constructor task to the request method. This.request here is the method of the ZIP_Ajax instance, and this points to the ZIP_Ajax instance. This after apply points to ZIP_Ajax. Finally, according to new The keyword will actually point this to the ZIP_Ajax class. With the definition of the class ZIP_Ajax, you can then define its method:

XMLHttpRequest Detailed explanation:

XMLHttpRequest is not a technology but a function built into mainstream browsers. Full access to http protocol objects. Most traditional http requests are based on form submission and request http, and then return a form. While XMLHttpRequest supports synchronous requests, the biggest advantage is that it supports asynchronous transmission and reception of data. Creating a new ajax request is actually instantiating an XMLHttpRequest object. A brief introduction to the main events and methods:

readystatechange event:

When XMLHttpRequest sends an http request, a readystatechange event will be triggered. The event returns five values. 0, 1, and 2 respectively represent the creation of XMLHttpRequest, completion of XMLHttpRequest initialization, and sending the request. 3 represents that the response has not ended (that is, only the response header data is received). 4 is the real response to the complete response.

The returned status status indicates the status code returned by the server:

The commonly used ones are 200 indicating successful return of data, 301 permanent redirection, and 302 temporary redirection (not Security) 304 reads cached data, 400 indicates a syntax error in the request, 403 indicates that the server rejects the request, 404 indicates that the requested web page resource does not exist, 405 cannot find the server at the specified location, 408 indicates that the request has timed out, 500 indicates an internal server error, and 505 indicates that the server The requested http protocol version is not supported.

200-300 indicates success, 300-400 indicates redirection, 400-500 indicates that the request content or format or the request body is too large causing an error, 500+ indicates an internal server error

open method:

open receives three parameters: request type (get, post, head, etc.), url, synchronous or asynchronous

send method:

When the request is ready, the send method will be triggered, and the content sent is the requested data (if it is a get request, the parameter is null;

After the request is successful, success will be executed Custom method whose parameters are return data;

ajax cross-domain:

What is cross-domain?

If two sites When www.a.com wants to request data from www.b.com, cross-domain problems occur due to inconsistent domain names. Even if the domain names are the same, if the ports are different, there will be cross-domain problems (for this reason, js can only stand by and watch. ). To determine whether it is cross-domain, just use window.location.protocol+window.location.host. For example, http://www.baidu.com.

js has several ways to solve cross-domain problems. Solution?

1. document.domain+iframe

For requests with the same main domain but different subdomains, domain name + iframe can be used as a solution. The specific idea is that there are two. Different ab files under the domain name www.a.com/a.html

and hi.a.com/b.html, we can add document.domain=" to the two html files a.com", and then create an iframe in the a file to control the contentDocument of the iframe, so that the two files can communicate. For example:

a on www.a.com. In the html file

document.domain="a.com";
  var selfFrame=document.createElement("iframe");
  selfFrame.src="http://hi.a.com/b.html";
  selfFrame.style.display="none";
  document.body.appendChild(selfFrame);
  selfFrame.onload=function(){
    var doc=selfFrame.contentDocument||selfFrame.contentWindow.document;//得到操作b.html权限
    alert(doc.getElementById("ok_b").innerHTML());//具体操作b文件中元素
  }
Copy after login

In the b.html file on hi.a.com

document.domain="a.com";

Problem:

1. Security. When one site (hi.a.com) is attacked, another site (www.a.com) will cause security holes. 2. If multiple pages are introduced. If you want to be able to operate all iframes, you must set the same domain.

2. Dynamically create scripts (the legendary jsonp method)

Browsers prohibit cross-domain access by default. , but it is not prohibited to reference js files of other domain names in the page, and methods introduced in js files can be executed. Based on this, we can achieve complete cross-domain communication by creating script node methods. The implementation steps are:

a. Dynamically load a script on the request initiator page. The url of the script points to the receiver's backend. The javascript method returned by the address will be executed by the initiator. The url can pass parameters. And only supports get submission parameters.

b. When loading the script, call the cross-domain js method for callback processing (jsonp).

For example:

Initiator

function uploadScript(options){
  var head=document.getElementsByTagName("head")[0];
  var script=document.createElement("script");
  script.type="text/javasctipt";
  options.src += &#39;?callback=&#39; + options.callback;
  script.src=options.src;
  head.insertBefore(script,head.firstChild);
}
function callback(data){}
window.onload=function(){//调用
  uploadScript({src:"http://e.com/xxx/main.ashx",callback:callback})
}
Copy after login

Receiver:

The receiver only needs to return an execution function , the execution function is the callback in the request and assigns parameters.

3. Use postMessage of html5:

One of the new features of html5 is cross-document message transmission, which is now supported and used by most browsers (including ie8+) , which supports web-based real-time messaging and has no cross-domain issues. postMessage is generally used with iframe.

举例如下:

父页面:

<iframe id="myPost" src="http//www.a.com/main.html"></iframe>
window.onload=function(){
  document.getElementById("myPost").contentWindow.postMessage("显示我","http://www.a.com")
  //第二个参数表示确保数据发送给适合域名的文档
}
a.com/main.html页面:
window.addEventListener("message",function(event){
  if(event.origin.indexOf("a.com")>-1){
    document.getElementById("textArea").innerHTML=event.data;
  }
},false)
<body>
  <p>
    <span id="textArea"></span>
  </p>
</body>
Copy after login

这样在父页面加载完成后main.html页面的textArea部分就会显示"显示我"三个字

ajax方法封装code:

ZIP_Ajax.prototype={
  request:function(url options){
    this.options=options;
    if(options.method=="jsonp"){//跨域请求
      return this.jsonp();
    }
    var httpRequest=this.http();
    options=Object.extend({method: 'get',
      async: true},options||{});
    
    if(options.method=="get"){
      url+=(url.indexOf('?')==-1?'?':'&')+options.data;
      options.data=null;
    }
    httpRequest.open(options.method,url,options.async);
    if (options.method == 'post') {
      httpRequest.setRequestHeader('Content-type', 'application/x-www-form-urlencoded; charset=UTF-8');
    }
    httpRequest.onreadystatechange = this._onStateChange.bind(this, httpRequest, url, options);
    httpRequest.send(options.data || null);//get请求情况下data为null
    return httpRequest;
  },
  jsonp:function(){
    jsonp_str = 'jsonp_' + new Date().getTime();
    eval(jsonp_str + ' = ' + this.options.callback + ';');    
    this.options.url += '?callback=' + jsonp_str;
    for(var i in this.options.data) {
      this.options.url += '&' + i + '=' + this.options.data[i];
    } 
    var doc_head = document.getElementsByTagName("head")[0],
      doc_js = document.createElement("script"),
      doc_js.src = this.options.url;
    doc_js.onload = doc_js.onreadystatechange = function(){
       if (!this.readyState || this.readyState == "loaded" || this.readyState == "complete"){
         //清除JS
         doc_head.removeChild(doc_js);      
        }
      }   
      doc_head.appendChild(doc_js);
  },
  http:function(){//判断是否支持xmlHttp
    if(window.XMLHttpRequest){
      return new XMLHttpRequest();
    }
    else{
      try{
        return new ActiveXObject('Msxml2.XMLHTTP')
      }
      catch(e){
        try {
          return new ActiveXObject('Microsoft.XMLHTTP');
        } catch (e) {
          return false;
        }
      }
    }
  },
  _onStateChange:function(http,url,options){
    if(http.readyState==4){
      http.onreadystatechange=function(){};//重置事件为空
      var s=http.status;
      if(typeof(s)=='number'&&s>200&&s<300){
        if(typeof(options.success)!='function')return;
        var format=http;
        if(typeof(options.format)=='string'){//判断请求数据格式
          switch(options.format){
            case 'text':
              format=http.responseText;
              break;
            case 'json':
              try{
                format=eval('('+http.responseText+')');
              }
              catch (e) {
                if (window.console && console.error) console.error(e);
              }
              break;
            case 'xml':
              format=http.responseXML;
              break;
          }
        }
      options.success(format);//成功回调
      }
      else {//请求出问题后处理
        if (window.closed) return;
        if (typeof (options.failure) == 'function') {
          var error = {
            status: http.status,
            statusText: http.statusText
          }
          //  判断是否是网络断线或者根本就请求不到服务器
          if (http.readyState == 4 && (http.status == 0 || http.status == 12030)) {
            //  是
            error.status = -1;
          }
          options.failure(error);
        }
      }
    } 
  }
};
Copy after login

使用方法:

ajax调用举例:

var myAjax=new ZIP_Ajax("http://www.a.com/you.php",{
  method:"get",
  data:"key=123456&name=yuchao",
  format:"json",
  success:function(data){
    ......
  }
})
跨域请求调用举例:
var jsonp=new ZIP_Ajax("http://www.a.com/you.php",{
  method:"jsonp",
  data:{key:"123456",name:"yuchao"},
  callback:function(data){
    ......
  }
})
Copy after login

相关推荐:

JS组件系列--组件封装深入:使用jquery data()和html 5 data-*属性初始化组件_html/css_WEB-ITnose

Ajax跨域的完美解决方案实例分享

最全ajax跨域解决方案

The above is the detailed content of Detailed explanation of custom ajax support for cross-domain component encapsulation. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to quickly set up a custom avatar in Netflix How to quickly set up a custom avatar in Netflix Feb 19, 2024 pm 06:33 PM

An avatar on Netflix is ​​a visual representation of your streaming identity. Users can go beyond the default avatar to express their personality. Continue reading this article to learn how to set a custom profile picture in the Netflix app. How to quickly set a custom avatar in Netflix In Netflix, there is no built-in feature to set a profile picture. However, you can do this by installing the Netflix extension on your browser. First, install a custom profile picture for the Netflix extension on your browser. You can buy it in the Chrome store. After installing the extension, open Netflix on your browser and log into your account. Navigate to your profile in the upper right corner and click

How to customize shortcut key settings in Eclipse How to customize shortcut key settings in Eclipse Jan 28, 2024 am 10:01 AM

How to customize shortcut key settings in Eclipse? As a developer, mastering shortcut keys is one of the keys to improving efficiency when coding in Eclipse. As a powerful integrated development environment, Eclipse not only provides many default shortcut keys, but also allows users to customize them according to their own preferences. This article will introduce how to customize shortcut key settings in Eclipse and give specific code examples. Open Eclipse First, open Eclipse and enter

How to solve the 403 error encountered by jQuery AJAX request How to solve the 403 error encountered by jQuery AJAX request Feb 20, 2024 am 10:07 AM

Title: Methods and code examples to resolve 403 errors in jQuery AJAX requests. The 403 error refers to a request that the server prohibits access to a resource. This error usually occurs because the request lacks permissions or is rejected by the server. When making jQueryAJAX requests, you sometimes encounter this situation. This article will introduce how to solve this problem and provide code examples. Solution: Check permissions: First ensure that the requested URL address is correct and verify that you have sufficient permissions to access the resource.

The operation process of edius custom screen layout The operation process of edius custom screen layout Mar 27, 2024 pm 06:50 PM

1. The picture below is the default screen layout of edius. The default EDIUS window layout is a horizontal layout. Therefore, in a single-monitor environment, many windows overlap and the preview window is in single-window mode. 2. You can enable [Dual Window Mode] through the [View] menu bar to make the preview window display the playback window and recording window at the same time. 3. You can restore the default screen layout through [View menu bar>Window Layout>General]. In addition, you can also customize the layout that suits you and save it as a commonly used screen layout: drag the window to a layout that suits you, then click [View > Window Layout > Save Current Layout > New], and in the pop-up [Save Current Layout] Layout] enter the layout name in the small window and click OK

How to solve jQuery AJAX request 403 error How to solve jQuery AJAX request 403 error Feb 19, 2024 pm 05:55 PM

jQuery is a popular JavaScript library used to simplify client-side development. AJAX is a technology that sends asynchronous requests and interacts with the server without reloading the entire web page. However, when using jQuery to make AJAX requests, you sometimes encounter 403 errors. 403 errors are usually server-denied access errors, possibly due to security policy or permission issues. In this article, we will discuss how to resolve jQueryAJAX request encountering 403 error

TrendForce: Nvidia's Blackwell platform products drive TSMC's CoWoS production capacity to increase by 150% this year TrendForce: Nvidia's Blackwell platform products drive TSMC's CoWoS production capacity to increase by 150% this year Apr 17, 2024 pm 08:00 PM

According to news from this site on April 17, TrendForce recently released a report, believing that demand for Nvidia's new Blackwell platform products is bullish, and is expected to drive TSMC's total CoWoS packaging production capacity to increase by more than 150% in 2024. NVIDIA Blackwell's new platform products include B-series GPUs and GB200 accelerator cards integrating NVIDIA's own GraceArm CPU. TrendForce confirms that the supply chain is currently very optimistic about GB200. It is estimated that shipments in 2025 are expected to exceed one million units, accounting for 40-50% of Nvidia's high-end GPUs. Nvidia plans to deliver products such as GB200 and B100 in the second half of the year, but upstream wafer packaging must further adopt more complex products.

PHP and Ajax: Building an autocomplete suggestion engine PHP and Ajax: Building an autocomplete suggestion engine Jun 02, 2024 pm 08:39 PM

Build an autocomplete suggestion engine using PHP and Ajax: Server-side script: handles Ajax requests and returns suggestions (autocomplete.php). Client script: Send Ajax request and display suggestions (autocomplete.js). Practical case: Include script in HTML page and specify search-input element identifier.

How to customize x-axis and y-axis in excel? (How to customize excel axis scale) How to customize x-axis and y-axis in excel? (How to customize excel axis scale) Mar 14, 2024 pm 02:10 PM

In an excel table, sometimes you may need to insert coordinate axes to see the changing trend of the data more intuitively. Some friends still don’t know how to insert coordinate axes in the table. Next, I will share with you how to customize the coordinate axis scale in Excel. Coordinate axis insertion method: 1. In the excel interface, select the data. 2. In the insertion interface, click to insert a column chart or bar chart. 3. In the expanded interface, select the graphic type. 4. In the right-click interface of the table, click Select Data. 5. In the expanded interface, you can customize it.

See all articles