search
HomeWeb Front-endJS TutorialCustom ajax cross-domain component packaging

Custom ajax cross-domain component packaging

Apr 12, 2018 pm 05:36 PM
ajaxencapsulationcustomize

This time I will bring you custom ajax cross-domain component encapsulation. What are the precautions when using custom ajax cross-domain component encapsulation? Here are actual cases, let’s take a look.

Class.create() analysis

Create class inheritance by imitating prototype

var Class = {
  create: function () {
    var c = function () {
      this.request.apply(this, arguments);
    }
    for (var i = 0, il = arguments.length, it; i <p style="text-align: left;">
ajax definition: ZIP_Ajax=Class.create();</p><p style="text-align: left;">
The create method returns a <a href="http://www.php.cn/wiki/176.html" target="_blank"> constructor </a>request, which is equivalent to var ZIP_Ajax= function(){
this.request.apply(this, arguments); };
Using object impersonation to perform a construction process inside the function is equivalent to handing over the constructor task to the request method. Here this.request is the method of the ZIP_Ajax instance, and this points to the ZIP_Ajax instance, after apply This points to ZIP_Ajax, and finally this actually points to the ZIP_Ajax class based on the new keyword. With the definition of class ZIP_Ajax, you can then define its methods: </p><p style="text-align: left;">
<strong>XMLHttpRequest detailed explanation: </strong></p><p style="text-align: left;">
XMLHttpRequest is not a technology but an object built into mainstream browsers that can fully access the http protocol. Most of the 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. Briefly introduce the main events and methods: </p><p style="text-align: left;">
<strong>readystatechange event: </strong></p><p style="text-align: left;">
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 initialization of XMLHttpRequest, and sending of the request. 3 represents that the response has not ended (that is, only the response has been received). Header data) 4 is the real way to get a complete response. </p><p style="text-align: left;">
The returned status indicates the status code returned by the server: </p><p style="text-align: left;">
Commonly used ones include 200 indicating successful return of data, 301 permanent redirection, 302 indicating temporary redirection (unsafe), 304 reading <a href="http://www.php.cn/code/9477.html" target="_blank"> cached data </a>, 400 indicating a <a href="http://www.php.cn/wiki/96.html" target="_blank"> syntax error </a> in the request, and 403 indicating The server rejects the request. 404 indicates that the requested web resource does not exist, 405 cannot find the server at the specified location, 408 indicates that the request has timed out, 500 internal server error, and 505 indicates that the server does not support the requested http protocol version. </p><p style="text-align: left;">
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, and 500 indicates an internal server error</p><p style="text-align: left;">
<strong>open method: </strong></p><p style="text-align: left;">
open receives three parameters: <a href="http://www.php.cn/php/php-tp-requesttype.html" target="_blank">Request type</a> (get, post, head, etc.), url, synchronous or asynchronous</p><p style="text-align: left;">
<strong>send method: </strong></p><p style="text-align: left;">
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; </p><p style="text-align: left;">
After the request is successful, the success custom method will be executed, and its parameter is the return data; </p><p style="text-align: left;">
<strong>ajax cross-domain: </strong></p><p style="text-align: left;">
What is cross-domain? </p><p style="text-align: left;">
If two sites www.a.com want to request data from www.b.com, there will be a cross-domain problem caused by inconsistent domain names. Even if the domain name is the same, if the ports are different, there will be cross-domain problems (for this reason, js can only sit back and watch). To determine whether it is cross-domain, just use window.location.protocol window.location.host to determine whether it is cross-domain. For example, http://www.baidu.com.</p><p style="text-align: left;">
What are several ways to solve cross-domain problems with js? </p><p style="text-align: left;">
<strong>1、document.domain iframe</strong></p><p style="text-align: left;">
For requests with the same main domain but different subdomains, domain name iframe can be used as a solution. The specific idea is that if there are two different ab files under two domain names www.a.com/a.html</p><p style="text-align: left;">
As well as hi.a.com/b.html, we can add document.domain="a.com" to the two html files, and then create an iframe in the a file to control the contentDocument of the iframe, so that the two files You can have a conversation. Examples are as follows: </p><p style="text-align: left;">
</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 a.html file on www.a.com

in the b.html file on hi.a.com document.domain="a.com";

question:

1、安全性,当一个站点(hi.a.com)被攻击后,另一个站点(www.a.com)会引起安全漏洞。2、如果一个页面中引入多个iframe,要想能够操作所有iframe,必须都得设置相同domain。

2、动态创建script(传说中jsonp方式)

浏览器默认禁止跨域访问,但不禁止在页面中引用其他域名的js文件,并且可以执行引入js文件中的方法等,根据这点我们可以通过创建script节点方法来实现完全跨域的通信。实现步骤为:

a.在请求发起方页面动态加载一个script,script的url指向接收方的后台,该地址返回的javascript方法会被发起方执行,url可以传参并仅支持get提交参数。

b.加载script脚本时候调用跨域的js方法进行回调处理(jsonp)。

举例如下:

发起方

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

接收方:

接收方只需要返回一个执行函数,该执行函数就是请求中的callback并赋参数。

3、使用html5的postMessage:

html5新功能有一个就是跨文档消息传输,如今大部分浏览器都已经支持并使用(包括ie8+),其支持基于web的实时消息传递并且不存在跨域问题。postMessage一般会跟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 style="text-align: left;">
	<span style="color:#ff0000;">使用方法:</span></p><p style="text-align: left;">
	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){
    ......
  }
})

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

express搭建查询服务器的方法

Django的cookie使用详解

The above is the detailed content of Custom ajax cross-domain component packaging. 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
The Future of Python and JavaScript: Trends and PredictionsThe Future of Python and JavaScript: Trends and PredictionsApr 27, 2025 am 12:21 AM

The future trends of Python and JavaScript include: 1. Python will consolidate its position in the fields of scientific computing and AI, 2. JavaScript will promote the development of web technology, 3. Cross-platform development will become a hot topic, and 4. Performance optimization will be the focus. Both will continue to expand application scenarios in their respective fields and make more breakthroughs in performance.

Python vs. JavaScript: Development Environments and ToolsPython vs. JavaScript: Development Environments and ToolsApr 26, 2025 am 12:09 AM

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

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

Video Face Swap

Video Face Swap

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

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft