Home Web Front-end JS Tutorial Native JS encapsulated Ajax plug-in (same domain, jsonp cross-domain)_javascript skills

Native JS encapsulated Ajax plug-in (same domain, jsonp cross-domain)_javascript skills

May 16, 2016 pm 03:02 PM
js encapsulation

実際のところ、ネイティブ JS に対するいわゆる馴染みとは何でしょうか?

最近私はネイティブ JS を使っておなじみの演習を行っています。 。 。

ネイティブ JS を使用して Ajax プラグインをカプセル化し、一般的なプロジェクトを導入し、データを転送します。 。 。考え方を簡単に説明してください。間違っているところがあれば修正してください^_^

1. Ajax コア、XHR オブジェクトの作成

Ajax テクノロジの中核は、XMLHttpRequest オブジェクト (略して XHR) です。IE5 の XHR オブジェクトは、MSXML ライブラリの ActiveX オブジェクトを通じて実装されているため、XHR オブジェクトを導入することができます。 IE MSXML2.XMLHttp、MSXML2.XMLHttp.3.0、MSXML2.XMLHttp.6.0 の 3 つのバージョンがあります。したがって、XHR オブジェクトを作成するときは、互換性のある記述を使用する必要があります:

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. XHR の主なメソッド属性

方法:

open() メソッド: 送信するリクエストのタイプ、リクエストの URL、非同期に送信するかどうかを示すブール値の 3 つのパラメータを受け入れます

send() メソッド: リクエスト本文として送信するデータ。リクエスト本文を通じてデータを送信する必要がない場合は、null

を渡す必要があります。

abort() メソッド: 非同期リクエストをキャンセルするための応答を受信する前に呼び出されます。

プロパティ:

responseText: 応答本文として返されるテキスト。

status: 応答の HTTP ステータス

statusText: HTTP ステータスの説明

readyState: 要求/応答プロセスの現在アクティブな段階を示します

の値は次のとおりです:

0: 初期化されていません。 open() メソッドはまだ呼び出されていません

1: 開始します。 open() メソッドは呼び出されていますが、send() メソッドはまだ呼び出されていません

2: 送信します。 send() メソッドが呼び出されましたが、応答が受信されませんでした。

3: 受け取ります。部分的な応答データを受信しました

4: 完了。すべての応答データが受信され、クライアントで使用できるようになりました。

この例の onreadystatechange イベント ハンドラー:

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

注: ブラウザ間の互換性を確保するには、open() メソッドを呼び出す前に onreadystatechange イベント ハンドラーを指定する必要があります。

3. 同じドメインでリクエストを送信します

①GETリクエスト

最も一般的なリクエスト タイプ。特定の情報をクエリするためによく使用されます。情報は、クエリの文字列パラメーターを URL の末尾に追加することによってサーバーに送信されます。 get メソッドのリクエストで注意すべき点の 1 つは、クエリ文字列内の各パラメーターの名前と値は encodeURIComponent() を使用してエンコードする必要があり、すべての名前と値のペアをアンパサンドで区切る必要があることです。

リクエスト方法:

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リクエスト

通常、サーバーに保存する必要があるデータを送信するために使用されます。POST リクエストでは、リクエストの本文としてデータを送信する必要があります。これにより、フォームの送信がシミュレートされます。つまり、Content-Type ヘッダー情報を application/x-www-form-urlencoded に設定します。

シリアル化関数:

 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

リクエスト方法:

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

两个请求的一些区别:

①GET请求把参数数据写到URL中,在URL中可以看到,而POST看不到,所以GET不安全,POST较安全。

②GET传送的数据量较小,不能大于2kb。POST传送的数据量较大,一般默认为不受限制。

③GET服务器端用Request.QueryString来获取变量的值,POST服务器端用Request.From来获取。

④GET将数据添加到URL中来传递到服务器,通常利用一个?,后面的参数每一个数据参数以“名称=值”的形式出现,参数与参数之间利用一个连接符&来区分。POST的数据是放在HTTP主体中的,其组织方式不只一种,有&链接方式,也有分隔符方式。可以隐藏参数,传递大批数据,比较方便。

四、jsonp跨域发送请求

首先,跨域是神马情况呢?

一个域名的组成:

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

以上就是本文的全部内容,希望对大家的学习有所帮助。

插件详细解析及使用方法见:https://github.com/LuckyWinty/AjaxPlugin

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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

How to create a stock candlestick chart using PHP and JS How to create a stock candlestick chart using PHP and JS Dec 17, 2023 am 08:08 AM

How to use PHP and JS to create a stock candle chart. A stock candle chart is a common technical analysis graphic in the stock market. It helps investors understand stocks more intuitively by drawing data such as the opening price, closing price, highest price and lowest price of the stock. price fluctuations. This article will teach you how to create stock candle charts using PHP and JS, with specific code examples. 1. Preparation Before starting, we need to prepare the following environment: 1. A server running PHP 2. A browser that supports HTML5 and Canvas 3

TrendForce: Nvidia's Blackwell platform products drive TSMC's CoWoS production capacity to increase by 150% this year TrendForce: Nvidia's Blackwell platform products drive TSMC's CoWoS production capacity to increase by 150% this year Apr 17, 2024 pm 08:00 PM

According to news from this site on April 17, TrendForce recently released a report, believing that demand for Nvidia's new Blackwell platform products is bullish, and is expected to drive TSMC's total CoWoS packaging production capacity to increase by more than 150% in 2024. NVIDIA Blackwell's new platform products include B-series GPUs and GB200 accelerator cards integrating NVIDIA's own GraceArm CPU. TrendForce confirms that the supply chain is currently very optimistic about GB200. It is estimated that shipments in 2025 are expected to exceed one million units, accounting for 40-50% of Nvidia's high-end GPUs. Nvidia plans to deliver products such as GB200 and B100 in the second half of the year, but upstream wafer packaging must further adopt more complex products.

How to use JS and Baidu Map to implement map click event processing function How to use JS and Baidu Map to implement map click event processing function Nov 21, 2023 am 11:11 AM

Overview of how to use JS and Baidu Maps to implement map click event processing: In web development, it is often necessary to use map functions to display geographical location and geographical information. Click event processing on the map is a commonly used and important part of the map function. This article will introduce how to use JS and Baidu Map API to implement the click event processing function of the map, and give specific code examples. Steps: Import the API file of Baidu Map. First, import the file of Baidu Map API in the HTML file. This can be achieved through the following code:

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

The relationship between js and vue The relationship between js and vue Mar 11, 2024 pm 05:21 PM

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

AMD 'Strix Halo” FP11 package size exposed: equivalent to Intel LGA1700, 60% larger than Phoenix AMD 'Strix Halo” FP11 package size exposed: equivalent to Intel LGA1700, 60% larger than Phoenix Jul 18, 2024 am 02:04 AM

This website reported on July 9 that the AMD Zen5 architecture "Strix" series processors will have two packaging solutions. The smaller StrixPoint will use the FP8 package, while the StrixHalo will use the FP11 package. Source: videocardz source @Olrak29_ The latest revelation is that StrixHalo’s FP11 package size is 37.5mm*45mm (1687 square millimeters), which is the same as the LGA-1700 package size of Intel’s AlderLake and RaptorLake CPUs. AMD’s latest Phoenix APU uses an FP8 packaging solution with a size of 25*40mm, which means that StrixHalo’s F

See all articles