JS encapsulates the same domain, jsonp cross-domain (with code)
This time I will bring you JS encapsulation in the same domain, jsonp cross-domain (with code), JS encapsulation in the same domain, jsonp cross-domain What are the precautions , the following is a practical case, let's take a look one time.
Use native Js to encapsulate an Ajax plug-in, introduce general projects, and transfer data. It feels feasible. . . Let me briefly talk about the ideas. If there are any mistakes, please correct me^_^
1. Ajax core, creating XHR objects
The core of Ajax technology is XMLHttpRequest Object (referred to as , MSXML2.XMLHttp.3.0 and MSXML2.XMLHttp.6.0. Therefore, when creating an XHR object, you must use compatibility writing:
createXHR:function(){ if(typeof XMLHttpRequest!='undefined'){ return new XMLHttpRequest(); }else if(typeof ActiveXObject!='undefined'){ if(typeof arguments.callee.activeXString!='string'){ var versions=["MSXML2.XMLHttp.6.0","MSXML2.XMLHttp.3.0","MSXML2.XMLHttp"],i,len; for(i=0,len=versions.length;i<len;i++){ try{ new ActiveXObject(versions[i]); arguments.callee.activeXString=versions[i]; break; }catch(ex){ } } return new ActiveXObject(arguments.callee.activeXString); }else{ throw new Error("No XHR object available."); } }
2. The main method attributes of XHR
Method:
open() method : Accepts 3 parameters, the type of request to be sent, the URL of the request, and the Boolean value of whether to send asynchronously
send() method: The data to be sent as the request body, if there is no need to send data through the request body , you must pass in null
abort() method: called to cancel the asynchronous request before receiving the response.
Properties:
responseText: The text returned as the response body.
status: HTTP status of the response
statusText: HTTP status description
readyState: Indicates the current active stage of the request/response process
The values are respectively :
0: Not initialized. The open() method has not been called
1: Start. The open() method has been called, but the send() method has not been called
2: Send. The send() method has been called, but no response has been received.
3: Receive. Partial response data has been received
4: Complete. All response data has been received and can be used on the client.
onreadystatechangeEvent handling in this exampleFunction:
var complete=function(){ if(xhr.readyState==4){ if((xhr.status>=200&&xhr.status<300)||xhr.status==304){ if(params.success){ params.success(xhr.responseText);//执行调用ajax时指定的success函数 } }else{ if(params.fail){ params.fail();//执行调用ajax时指定的fail函数 }else{ throw new Error("Request was unsucessful:"+xhr.status); } } } }
Note: The onreadystatechange event handling function must be specified before calling the open() method to ensure cross-browser compatibility .
3. Sending requests in the same domain
①GET request
The most common request type, often used to query certain information. Information is sent to the server by appending the query's string parameters to the end of the URL. One thing to note with get method requests is that each parameter name and value in the query string must be encoded using encodeURIComponent(), and all name-value pairs must be separated by an ampersand.
Request method:
if((this.config.type=="GET")||(this.config.type=="get")){ for(var item in this.config.data){ this.config.url=addURLParam(this.config.url,item,this.config.data[item]);//使用encodeURIComponent()进行编码 } xhr.onreadystatechange=complete; xhr.open(this.config.type,this.config.url,this.config.async); xhr.send(null); }
②POST request
is usually used to send data that should be saved to the server. The POST request should submit the data as the body of the request. This will simulate a form submission. That is, set the Content-Type header information to application/x-www-form-urlencoded; charset=UTF-8.
Serialization function:
function serialize(data){ var val=""; var str=""; for(var item in data){ str=item+"="+data[item]; val+=str+'&'; } return val.slice(0,val.length-1); }
Request method:
if(this.config.type=="POST"||this.config.type=="post"){ xhr.addEventListener('readystatechange',complete); xhr.open(this.config.type,this.config.url,this.config.async); if(params.contentType){ this.config.contentType=params.contentType; } xhr.setRequestHeader("Content-Type",this.config.contentType); xhr.send(serialize(this.config.data)); }
Some differences between the two requests:
①GET request writes parameter data to the URL, It can be seen in the URL, but not in POST, so GET is not safe and POST is safer.
②The amount of data transmitted by GET is small and cannot be larger than 2kb. The amount of data transmitted by POST is relatively large and is generally unrestricted by default.
③The GET server side uses Request.QueryString to obtain the value of the variable, and the POST server side uses Request.From to obtain it.
④GET adds data to the URL to pass to the server, usually using a? , each data parameter in the following parameters appears in the form of "name=value", and the parameters are distinguished by a connector &. POST data is placed in the HTTP body, and it is organized in more than one way, including & links and delimiters. You can hide parameters and transfer large amounts of data, which is more convenient.
4. JSONP sends cross-domain requests
First of all, what is the situation of cross-domain?
Composition of a domain name:
http:// www . abc.com: 8080 / scripts/AjaxPlugin.js
协议 子域名 主域名 端口号 请求资源地址
~当协议、子域名、主域名、端口号中任意一个不相同时,都算作不同于。
~不同域之间互相请求资源,就算作“跨域”。
所有的浏览器都遵守同源策略,这个策略能够保证一个源的动态脚本不能读取或操作其他源的http响应和cookie,这就使浏览器隔离了来自不同源的内容,防止它们互相操作。所谓同源是指协议、域名和端口都一致的情况。浏览器会阻止ajax请求非同源的内容。
JSONP(JSON with Padding) 是一种跨域请求方式。主要原理是利用了script 标签可以跨域请求的特点,由其 src 属性发送请求到服务器,服务器返回 JS 代码,网页端接受响应,然后就直接执行了,这和通过 script 标签引用外部文件的原理是一样的。但是jsonp跨域只支持get请求。
JSONP由两部分组成:回调函数和数据,回调函数一般是由网页端控制,作为参数发往服务器端,服务器端把该函数和数据拼成字符串返回。
jsonp跨域主要需要考虑三个问题:
1、因为 script 标签的 src 属性只在第一次设置的时候起作用,导致 script 标签没法重用,所以每次完成操作之后要移除;
2、JSONP这种请求方式中,参数依旧需要编码;
3、如果不设置超时,就无法得知此次请求是成功还是失败;
由于代码有点长,就放个计时器的代码吧,完整代码见AjaxPlugin
//超时处理 if(params.time){ scriptTag.timer=setTimeout(function(){ head.removeChild(scriptTag); params.fail&¶ms.fail({message:"over time"}); window[cbName]=null; },params.time); }
相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!
推荐阅读:
The above is the detailed content of JS encapsulates the same domain, jsonp cross-domain (with code). For more information, please follow other related articles on the PHP Chinese website!

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

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

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

Hot Topics

Some users encountered errors when installing the device, prompting error code 28. In fact, this is mainly due to the driver. We only need to solve the problem of win7 driver code 28. Let’s take a look at what should be done. Do it. What to do with win7 driver code 28: First, we need to click on the start menu in the lower left corner of the screen. Then, find and click the "Control Panel" option in the pop-up menu. This option is usually located at or near the bottom of the menu. After clicking, the system will automatically open the control panel interface. In the control panel, we can perform various system settings and management operations. This is the first step in the nostalgia cleaning level, I hope it helps. Then we need to proceed and enter the system and

What to do with blue screen code 0x0000001? The blue screen error is a warning mechanism when there is a problem with the computer system or hardware. Code 0x0000001 usually indicates a hardware or driver failure. When users suddenly encounter a blue screen error while using their computer, they may feel panicked and at a loss. Fortunately, most blue screen errors can be troubleshooted and dealt with with a few simple steps. This article will introduce readers to some methods to solve the blue screen error code 0x0000001. First, when encountering a blue screen error, we can try to restart

The win10 system is a very excellent high-intelligence system. Its powerful intelligence can bring the best user experience to users. Under normal circumstances, users’ win10 system computers will not have any problems! However, it is inevitable that various faults will occur in excellent computers. Recently, friends have been reporting that their win10 systems have encountered frequent blue screens! Today, the editor will bring you solutions to different codes that cause frequent blue screens in Windows 10 computers. Let’s take a look. Solutions to frequent computer blue screens with different codes each time: causes of various fault codes and solution suggestions 1. Cause of 0×000000116 fault: It should be that the graphics card driver is incompatible. Solution: It is recommended to replace the original manufacturer's driver. 2,

Termination Code 0xc000007b While using your computer, you sometimes encounter various problems and error codes. Among them, the termination code is the most disturbing, especially the termination code 0xc000007b. This code indicates that an application cannot start properly, causing inconvenience to the user. First, let’s understand the meaning of termination code 0xc000007b. This code is a Windows operating system error code that usually occurs when a 32-bit application tries to run on a 64-bit operating system. It means it should

Blue screen is a problem we often encounter when using the system. Depending on the error code, there will be many different reasons and solutions. For example, when we encounter the problem of stop: 0x0000007f, it may be a hardware or software error. Let’s follow the editor to find out the solution. 0x000000c5 blue screen code reason: Answer: The memory, CPU, and graphics card are suddenly overclocked, or the software is running incorrectly. Solution 1: 1. Keep pressing F8 to enter when booting, select safe mode, and press Enter to enter. 2. After entering safe mode, press win+r to open the run window, enter cmd, and press Enter. 3. In the command prompt window, enter "chkdsk /f /r", press Enter, and then press the y key. 4.

If you need to program any device remotely, this article will help you. We will share the top GE universal remote codes for programming any device. What is a GE remote control? GEUniversalRemote is a remote control that can be used to control multiple devices such as smart TVs, LG, Vizio, Sony, Blu-ray, DVD, DVR, Roku, AppleTV, streaming media players and more. GEUniversal remote controls come in various models with different features and functions. GEUniversalRemote can control up to four devices. Top Universal Remote Codes to Program on Any Device GE remotes come with a set of codes that allow them to work with different devices. you may

What does the 0x000000d1 blue screen code mean? In recent years, with the popularization of computers and the rapid development of the Internet, the stability and security issues of the operating system have become increasingly prominent. A common problem is blue screen errors, code 0x000000d1 is one of them. A blue screen error, or "Blue Screen of Death," is a condition that occurs when a computer experiences a severe system failure. When the system cannot recover from the error, the Windows operating system displays a blue screen with the error code on the screen. These error codes

Quickly get started with Python drawing: code example for drawing Bingdundun Python is an easy-to-learn and powerful programming language. By using Python's drawing library, we can easily realize various drawing needs. In this article, we will use Python's drawing library matplotlib to draw a simple graph of ice. Bingdundun is a cute panda who is very popular among children. First, we need to install the matplotlib library. You can do this by running in the terminal
