search
HomeWeb Front-endJS TutorialDetailed explanation of custom ajax support for cross-domain component encapsulation

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 <p>ajax definition: ZIP_Ajax=Class.create();<br> </p><p>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: </p><p>XMLHttpRequest Detailed explanation: <br></p><p>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: <br></p><p>readystatechange event: <br></p><p>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. <br></p><p>The returned status status indicates the status code returned by the server: <br></p><p>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. <br></p><p>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<br></p> <p>open method: <br></p><p>open receives three parameters: request type (get, post, head, etc.), url, synchronous or asynchronous <br></p><p>send method: <br></p><p>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; <br></p><p>After the request is successful, success will be executed Custom method whose parameters are return data;<br></p><p>ajax cross-domain:<br></p><p>What is cross-domain? <br></p><p>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.<br></p><p>js has several ways to solve cross-domain problems. Solution? <br></p><p>1. document.domain+iframe</p><p> 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<br></p><p> 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: <br></p><p>a on www.a.com. In the html file</p><pre class="brush:php;toolbar:false">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文件中元素
  }

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 += '?callback=' + 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})
}

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></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)

  <p>
    <span></span>
  </p>

这样在父页面加载完成后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<p>使用方法:<br></p><p>ajax调用举例:</p><pre class="brush:php;toolbar:false">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){
    ......
  }
})

相关推荐:

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
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
JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment