Home > Web Front-end > JS Tutorial > body text

JS encapsulates the same domain, jsonp cross-domain (with code)

php中世界最好的语言
Release: 2018-04-26 14:41:31
Original
1719 people have browsed it

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.");
 }
}
Copy after login

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);
 }
 }
 }
}
Copy after login

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);
}
Copy after login

②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);
 }
Copy after login

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));
}
Copy after login

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&&params.fail({message:"over time"});
 window[cbName]=null;
 },params.time);
}
Copy after login

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

推荐阅读:

jQuery设置键盘切换文本框焦点

JQuery设置文字框获取焦点样式(附代码)

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template