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中文网其它相关文章!
推荐阅读:
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!

Scrapy是一个开源的Python爬虫框架,它可以快速高效地从网站上获取数据。然而,很多网站采用了Ajax异步加载技术,使得Scrapy无法直接获取数据。本文将介绍基于Ajax异步加载的Scrapy实现方法。一、Ajax异步加载原理Ajax异步加载:在传统的页面加载方式中,浏览器发送请求到服务器后,必须等待服务器返回响应并将页面全部加载完毕才能进行下一步操

作为一种基于MVC模式的PHP框架,CakePHP已成为许多Web开发人员的首选。它的结构简单,易于扩展,而其中的AJAX技术更是让开发变得更加高效。在本文中,将介绍如何使用CakePHP中的AJAX。什么是AJAX?在介绍如何在CakePHP中使用AJAX之前,我们先来了解一下什么是AJAX。AJAX是“异步JavaScript和XML”的缩写,是指一种在

jquery ajax报错403是因为前端和服务器的域名不同而触发了防盗链机制,其解决办法:1、打开相应的代码文件;2、通过“public CorsFilter corsFilter() {...}”方法设置允许的域即可。

ajax传递中文乱码的解决办法:1、设置统一的编码方式;2、服务器端编码;3、客户端解码;4、设置HTTP响应头;5、使用JSON格式。详细介绍:1、设置统一的编码方式,确保服务器端和客户端使用相同的编码方式,通常情况下,UTF-8是一种常用的编码方式,因为它可以支持多种语言和字符集;2、服务器端编码,在服务器端,确保将中文数据以正确的编码方式进行编码,再传递给客户端等等。

404页面基础配置404错误是www网站访问容易出现的错误。最常见的出错提示:404notfound。404错误页的设置对网站seo有很大的影响,而设置不当,比如直接转跳主页等,会被搜索引擎降权拔毛。404页面的目的应该是告诉用户:你所请求的页面是不存在的,同时引导用户浏览网站其他页面而不是关掉窗口离去。搜索引擎通过http状态码来识别网页的状态。当搜索引擎获得了一个错误链接时,网站应该返回404状态码,告诉搜索引擎放弃对该链接的索引。而如果返回200或302状态码,搜索引擎就会为该链接建立索引

ajax重构指的是在不改变软件现有功能的基础上,通过调整程序代码改善软件的质量、性能,使其程序的设计模式和架构更合理,提高软件的扩展性和维护性;Ajax的实现主要依赖于XMLHttpRequest对象,由于该对象的实例在处理事件完成后就会被销毁,所以在需要调用它的时候就要重新构建。

CSRF代表跨站请求伪造。CSRF是未经授权的用户冒充授权执行的恶意活动。Laravel通过为每个活动用户会话生成csrf令牌来保护此类恶意活动。令牌存储在用户的会话中。如果会话发生变化,它总是会重新生成,因此每个会话都会验证令牌,以确保授权用户正在执行任何任务。以下是访问csrf_token的示例。生成csrf令牌您可以通过两种方式获取令牌。通过使用$request→session()→token()直接使用csrf_token()方法示例<?phpnamespaceApp\Http\C

当提交表单时,捕获提交过程并尝试运行以下代码片段来上传文件-//File1varmyFile=document.getElementById('fileBox').files[0];varreader=newFileReader();reader.readAsText(file,'UTF-8');reader.onload=myFunc;functionmyFunc(event){ varres


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1
Powerful PHP integrated development environment
