Home  >  Article  >  Web Front-end  >  A brief history and basic usage of Ajax

A brief history and basic usage of Ajax

php中世界最好的语言
php中世界最好的语言Original
2018-03-31 13:33:311206browse

This time I will bring you a brief history and basic usage of Ajax. What are the precautions to understand the brief history and usage of Ajax. Here are practical cases, let’s take a look.

Over the past few years, JavaScript has gone from being an incidental afterthought to being the most important language on the web. If there's one factor that has driven significant advancements in this technology, it's the emergence of Ajax-based application development.

Developing technologies on this topic

In short, Ajax is a development technology that supports a website or application using real-time data Update interface without page refresh. This feature creates a smoother and more desktop-like user experience.

A brief history of Ajax

The history of Ajax is similar to that of many other overnight successes. Although Ajax seems to have come out of nowhere, in fact, it has been around for a long time. Years of hard work have made it all over the web, creating tools and patterns under the Ajax banner. Throughout the DHTML days of the original dot-com bubble and the dark ages after dot-com bankruptcies, developers around the world unlocked the superpowers of JavaScript and brought this new and exciting application paradigm to the Web.

XMLHttpRequest

The earliest and most important Ajax puzzle is the XMLHttpRequest (XHR) API. XHR is a JavaScript API for transmitting data messages between web browsers and web servers. It supports browsers using HTTP POST (transmitting data to the server) or GET requests (accessing data from the backend server). This API is at the core of most Ajax interactions and is an essential technology in modern web development.

It is also the best gift the Microsoft® Internet Explorer® team has contributed to the Internet.

This is real. XHR first appeared in IE 5 back in 2000. Originally a Microsoft ® ActiveX ® control written by Alex Hopmann, XHR was created to work with Microsoft Outlook ® Web Access and was intended to address interactions between high-level (at the time) front-end interfaces and Microsoft Exchange Server.

Although Microsoft's software package is not exactly "from humble beginnings", XHR has evolved far beyond the scope of the original product, and has since been implemented in every major browser and even adopted as a W3C standard. .

Pioneer

In addition to Microsoft, there are some other companies that have begun to enter the field of prototype Ajax. Many businesses are experimenting with these technologies, but two in particular deserve mention -- one because it's an interesting and oft-cited footnote to Ajax development, and the other because it was the Internet giant that really democratized these technologies.

Oddpost

Oddpost is an advanced web-based email client launched in 2002. It utilizes many currently familiar patterns. In terms of design and interaction, desktop mail clients come to mind. Internally, Oddpost uses a concept the developers call DataPacks to transfer small chunks of data from the server to the browser. This will bring a new experience.

Oddpost was finally replaced by Yahoo! Acquired to become the basis for a revised version of Yahoo! Mail.

Google Maps, Google Suggest, Gmail, and an important article

The real changes started a few years later with Gmail, Google Suggest, and Google Maps service. The use of these three Ajax technologies has the web development world buzzing. Its responsiveness and interactivity are new to the public. The new Google app is quickly creating a buzz.

Although not many people know about it, the response from the web development community is very violent. At the time, people knew there was something new and exciting in web application development. But for a long time, this "content" was unclear.

What people need is an article that makes this clear.

On February 18, 2005, Jesse James Garrett, co-founder and president of Adaptive Path, wrote an article titled "Ajax: A New Approach to Web Applications." In this article, he describes trends in web application design and development, such as Gmail and Google Maps, which people use all the time. He calls the trend "potentially triggering fundamental changes in web development."

He also gave this pattern a name, which was an important moment because from this moment on people started focusing on this new trend and everyone (even non-experts) talked about the latest changes in the web development world. will all mention it. In this article, he introduces the technology of Ajax like this:

Definition of Ajax

Ajax is not a technology. It's actually several technologies, each with its own characteristics, that come together in new and powerful ways. Ajax includes:

  1. Standards-based rendering using XHTML and CSS

  2. Dynamic display and interaction using the Document Object Model

  3. Data exchange and manipulation using XML and XSLT

  4. Asynchronous data retrieval using XMLHttpRequest

  5. Bind them to JavaScript together

Although this technical description is somewhat outdated, the basic pattern is still intact: HTML and CSS render data and styles, DOM and related method support Pages update in real time, XHR supports communication with the server, and JavaScript arranges the overall display.

The overall impact of this article is relatively large. It’s a rare occasion when intense hype collides with untapped creativity and energy to create a revolution. As Ajax is adopted by a new generation of startups around the world, it is rapidly moving to the forefront of the web development paradigm. Ajax has gone from being a vague trend seeking marketing strategies to becoming a critical component in the development of modern Web design.

Libraries

A key driver of Ajax-based development is the evolution and improvement of several full-featured JavaScript libraries. Apart from experienced JavaScript developers, few people truly understand the underlying technology of Ajax. So even in the days of DHTML, while most browser interactions and animations were worked out to deal with trivial overage, the demand and talent for Ajax-based sites (who could be written from scratch) was limited by the limited number of experienced JavaScript engineers. Such an interface) further widens the gap between supply. Libraries like Prototype, Dojo, and jQuery help fill this gap at scale by providing ready-to-use interactions and animations, reducing cross-browser differences, and improving implementation of core JavaScript API shortcomings.

Asynchronous JavaScript and more JavaScript (Object Notation)

The biggest change in the Ajax field from the original post era to modern times is the introduction of JSON, JSON is a JavaScript-based data transmission. Offering smaller file sizes and easier native JavaScript access (as opposed to the clunky DOM-based methods and properties used by XML), JSON was quickly adopted by developers for data transfer. JSON is now included in the recently completed version 5 of the ECMAScript specification.

JSON+Padding

One proposed significant enhancement to raw JSON is JSON+Padding (JSONP). As you can see, the XMLHttpRequest object has a strict security model and only supports communication using the same domain name and protocol as the requested page. JSONP creates a more flexible approach to this cross-domain restriction by wrapping the JSON response into a user-defined or system-provided callback function. This method will provide instant data access after adding the JSON script to the document. This pattern is now common, and for many larger web services the practice can be adopted to support mashups and other content syndication.

Despite its popularity, JSONP has an obvious vulnerability that can easily be exploited by malicious code. Because script tag injection from a third party allows all content to be run on the host page, the potential for malicious compromise is imaginable if the data provider is compromised, or if the host page is not aware of the resources inserted into the page.

Now that you know a little bit about the history of Ajax, we'll start exploring the techniques that make the magic a reality. Although, general JavaScript API books are widely available in libraries, understanding how the underlying workings are still instructive even for experienced developers.

XMLHttpRequest API and Features

Although other technologies can be used to return data from the server, XHR remains at the core of most Ajax interactions. XHR interactions consist of two parts: requests and responses. Below we will introduce them one by one.

Security Model

As mentioned above, the original XMLHttpRequest object has a strict security model. This same-origin policy only allows communication using the same host, protocol, and port as the requested page. This means different domains (example.com and example2.com), different hosts (my.example.com and www.example.com), different protocols (http://example.com and https://example.com) Communication between is prohibited, which will generate error messages.

With the development of the second version of the XHR object, the new cross-domain request protocol work will be completed in the W3C. A large amount of implementation work is completed by browser vendors. The mechanism for cross-domain requests is currently only available in Internet Explorer. 8+, Mozilla Firefox 3.5+, Apple Safari 4+, and Google Chrome. Although development has slowed down, a specific "Origin" header is still sent in the request:

Origin: http://example.com

and the server Configured to send back a matching "Access-Control-Allow-Origin" header:

Access-Control-Allow-Origin: :http://example.com

Now, you can use XHR objects for two-way communication across domains.

Request

The request side has 4 methods:

  1. open() initiates a server connection . Can take parameters:

    1. method. The HTTP method to be used (can be POST or GET)

    2. url. Requested URL

    3. async. Optional Boolean parameter indicating whether the request is asynchronous (the default value of this parameter is True)

    4. user. An optional username for authentication using

    5. password. An optional password for authentication

  2. setRequestHeader() sets the request header, with two parameters: the header and its associated values

  3. send() Sends a request. This method takes an optional parameter, containing the body of the POST request

  4. abort() Abort the request

Response

The response also has several properties and methods :

  1. ##status. The standard HTTP status of the request (for example, a successful request will return 200)

  2. statusText. Includes the full response string returned by the web server, including the response text (for example, 304 Not Modified)

  3. getResponseHeader(). Returns specific header content; the request header name is its only parameter

  4. getAllResponseHeaders(). Returns the text

  5. responseText of all response headers. A string representation of the response text

  6. responseXML. XML representation of the response text, a document fragment containing the DOM and all related DOM methods

readyState

instantiation After completion, the XMLHttpRequest object has 5 states, represented by the following values:

  • 0: UNSENT. Indicates that the object has been created

  • 1: OPENED. Indicates that the open() method has been successfully called

  • 2: HEADERS_RECEIVED. Indicates that the header from the request was received

  • 3: LOADING. Indicates that the response header has been downloaded

  • 4: DONE. Indicates that the request was completed, but does not indicate whether the request was successful or return expected values ​​(query the response and standard HTTP headers to gauge the health of the request)

A generic JavaScript Examples

Before we go further into popular libraries, let's go through a few raw JavaScript examples to understand the core technology in action.

Sample HTML Document

<!doctype html>
<html lang="en"> 
<head>
 <meta charset="utf-8">
 <title>Simple Ajax Example</title>
 <meta name="author" content="Rob Larsen">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <link rel="stylesheet" href="_assets/css/style.css" rel="external nofollow" >
</head>
<body>
 <p id="main">
  <h1>Simple Ajax Example</h1>
  <p><strong id="activate">Click here</strong> 
   and content will be appended after this paragraph</p>
 </p>
 <script src="_assets/js/ajax.js"></script>
</body>
</html>
The following example illustrates a simple GET request that will handle responseXML. This is a typical Ajax interaction from the early days of the technology. It works in all modern browsers as well as Internet Explorer 7 and 8.

A basic Ajax function

/*
Here's a basic Ajax function
*/
var ajax = function( opts ) {
/*
We have an options argument. 
In addition, we want to have some smart defaults.
*/
 opts = {
  //Is it a Get or Post
  type: opts.type || "POST",
  //What URL are we going to hit?
  url: opts.url || "",
  //What do we do with the data
  onSuccess: opts.onSuccess || function(){},
  //what kind of data do we expect?
  data: opts.data || "xml"
 };
//create a new XMLHttpRequest 
 var xhr = new XMLHttpRequest();
//Open the connection to the server 
 xhr.open(opts.type, opts.url, true);
/*
When the ready state changes
fire this function
*/
 xhr.onreadystatechange = function(){
 //readyState 4 is "done" 
 if ( xhr.readyState == 4 ) {
 /*
 do some simple data processing
 There are two components to the returned object-
 responseXML and responseText. 
 Depending on what we're doing we'll need one or the other.
 */
 switch (opts.data){
  case "json":
   //json is text
   opts.onSuccess(xhr.responseText);
   break;
  case "xml":
   //XML retains the structure/DOM 
   //It's passed in whole. 
   opts.onSuccess(xhr.responseXML);
   break;
  default : 
   //Everything else will get TXT
   opts.onSuccess(xhr.responseText);;
  }   
 }
 };
 //close the connection
 xhr.send(null);
}
//here's our simple function
var ajaxSample = function(e){
//Simple callback adds some text to the page 
 var callback = function( data ) {
 document.getElementById("main").innerHTML += 
  "<p>"
  +data.getElementsByTagName("data")[0].getAttribute("value")
  +"</p>";
}
//And here's our Ajax call 
 ajax({
  type: "GET",
  url: "_assets/data/ajax-1.xml",
  onSuccess: callback,
  data : "xml"
 })
//prevent the default action 
 e.preventDefault();
}
//Wire everything up
document.getElementById("activate").addEventListener("click", ajaxSample, false);

在下面的例子 中可以看到活动的原始 ActiveX 对象。如果没有本机实现,可以在不同版本的 Internet Explorer 中使用 Try... Catch 块来循环遍历对象的潜在引用。这个完整的跨浏览器实现与 Internet Explorer 是兼容的,甚至可以与古老的 Internet Explorer 5 兼容。

 一个跨浏览器 Ajax 脚本

var ajax = function( opts ) {
 opts = {
 type: opts.type || "POST",
 url: opts.url || "",
 onSuccess: opts.onSuccess || function(){},
 data: opts.data || "xml"
 };
/*
Support for the original ActiveX object in older versions of Internet Explorer
This works all the way back to IE5.
*/
 if ( typeof XMLHttpRequest == "undefined" ) {
 XMLHttpRequest = function () {
  try { 
   return new ActiveXObject("Msxml2.XMLHTTP.6.0"); 
  }
  catch (e) {}
  try { 
   return new ActiveXObject("Msxml2.XMLHTTP.3.0"); 
  }
  catch (e) {}
  try { 
   return new ActiveXObject("Msxml2.XMLHTTP"); 
  }
  catch (e) {}
  throw new Error("No XMLHttpRequest.");
 };
 }
 var xhr = new XMLHttpRequest();
 xhr.open(opts.type, opts.url, true);
 xhr.onreadystatechange = function(){
 if ( xhr.readyState == 4 ) {
  switch (opts.data){
  case "json":
   opts.onSuccess(xhr.responseText);
   break;
  case "xml":
   opts.onSuccess(xhr.responseXML);
   break;
  default : 
   opts.onSuccess(xhr.responseText);;
  }   
 }
 };
 xhr.send(null);
}
var ajaxSample = function(e){
 var callback = function( data ) {
 document.getElementById("main").innerHTML += "<p>"
  +data.getElementsByTagName("data")[0].getAttribute("value")
  +"</p>";
 }
 ajax({
 type: "GET",
 url: "_assets/data/ajax-1.xml",
 onSuccess: callback,
 data: "xml"
 })
 e.preventDefault();
}
document.getElementById("activate").addEventListener("click", ajaxSample, false);

下面展示了现今更为常见的模式:采用 JSON 格式的 responseText,并将其解析成本机的 JavaScript 对象。这段代码演示了一个较为简单的 JSON 数据处理方法。为什么众多开发人员都选择使用 JSON 来传输数据,将该清单与操作 XML 数据所需的偶尔间接且冗长的方法进行比较,答案显而易见。

使用 JSON

var ajax = function( opts ) {
 opts = {
 type: opts.type || "POST",
 url: opts.url || "",
 onSuccess: opts.onSuccess || function(){},
 data: opts.data || "xml"
 };
 var xhr = new XMLHttpRequest();
 xhr.open(opts.type, opts.url, true);
 xhr.onreadystatechange = function(){
 if ( xhr.readyState == 4 ) {
  switch (opt.sdata){
  case "json":
   opt.onSuccess(xhr.responseText);
   break;
  case "xml":
   opt.onSuccess(xhr.responseXML);
   break;
  default : 
   opt.onSuccess(xhr.responseText);;
  }   
 }
 };
 xhr.send(null);
}
var jsonSample = function(e){
 var callback = function( data ) {
 //here, the data is actually a string
 //we use JSON.parse to turn it into an object
 data = JSON.parse(data);
 /*
 we can then use regular JavaScript object references
 to get at our data. 
 */
 document.getElementById("main").innerHTML += "<p>"
  + data.sample.txt 
  +"</p>";
 }
 ajax({
 type: "GET",
 url: "_assets/data/json-1.json",
 onSuccess: callback,
 data : "json"
 })
 e.preventDefault();
}
document.getElementById("activate").addEventListener("click", jsonSample, false);

下面例子都使用了 JSON 数据。

提供了一个简单的 JSONP 示例。正如您所看到的,通过使用一个回调参数,可以避免将 XHR 完全地简单附加到脚本中。返回给回调,并在可执行 JavaScript 代码中包装数据对象。

JSONP 数据

var callback = function( data ) {
 document.getElementById("main").innerHTML += "<p>"+ data.sample.txt +"</p>";
}
var jsonpSample = function(e){
//create a script element
 var jsonp = document.createElement("script");
//give it a source with the callback name appended in the query string
 jsonp.src= "_assets/data/jsonp.do?callback=callback";
//add it to the doc
 document.body.appendChild(jsonp);
 e.preventDefault();
}
//wire up the event
document.getElementById("activate").addEventListener("click", jsonpSample, false);

库示例

对于大多数开发人员来说,只有进行学术研究的人才会对 Ajax 请求的本质感兴趣。大多数实际工作是在一个或多个 JavaScript 库中完成。除了修补跨浏览器不兼容性,这些库都提供了构建于基础 API 之上的特性。下列示例展示了 3 个流行库中的 GET 和 POST 示例来介绍不同的 API。

jQuery

让我们从流行 jQuery 库开始举例说明。jQuery 的 Ajax 函数最近进行了重写,将几个高级功能包含在内,这不是术语本文的讨论范围,但是所有 jQuery Ajax 请求的常见功能都以传递给该函数的配置对象的参数形式存在。另外还要注意的是,jQuery 有几个便利的方法,比如 $.post 和$.get,这是常见请求配置的快捷键。
展示了使用 jQuery 获取数据的简要代码。

一个 jQuery GET 请求

/*
callback is a simple function that will be run
when the data is returned from the server
*/
var callback = function( data ) {
/* 
it just adds a little bit of text to the document
data is the JSON object returned by the server. 
*/
 $("#main").append($("<p />").text(data.sample.txt));
}
/*
Wire up the ajax call to this click event
*/
$("#activate").click(
 function(){
//call $.ajax with a configuration object 
 $.ajax({
//it's just a get request
  type: 'get',
//we're looking for this URL 
  url: '_assets/data/json-1.json',
//Our cool callback function
  success: callback,
//it's going to be JSON 
  dataType: "json"
 })
 } 
)

下面演示了如何发布和检索简单 JSON 对象。需要注意的是,这里使用了原生 JSON 对象来分析输入数据。jQuery 文档明确提及需要通过 JSON2.js 脚本增加不受支持的浏览器。

提供一个显式错误句柄使得成功请求和失败请求都能得到优雅的处理。jQuery 的错误状态带有 3 个参数,包括 XHR 对象本身,这支持健壮的错误处理

一个 jQuery POST

/*
this is the object we're going to post
*/
var myMessages = {
 positive : "Today is a good day",
 negative : "Today stinks",
 meh : "meh"
}
var callback = function( data ) {
 $("#main").append($("<p />").text(data.positive));
}
/*
Setting up a simple error handler.
It doesn't do much. 
It's just nice to illustrate error handling.
*/
var errorHandler = function( xhr, textStatus, errorThrown ){
 throw new Error("There was an error. The error status was " + textStatus );
}
/*
Here's where the action happens.
Attach an event to out simple button.
*/
$("#activate").click(
 function(){
//call $.ajax with a configuration object 
  $.ajax({
   //we're sending data to the server  
   type: 'POST',
   //this is our URL
   url: '_assets/data/post-responder.do',
   /*
   This is our data, JSON stringified
   jQuery expects to use native JSON
   or JSON2.js in unsupported browsers
   */
   data: JSON.stringify(myMessages),
   //Here's where we set up our callback function
   success: callback,
   //The data expected from the server
   dataType: "json",
   //And our simple error handler
   error : errorHandler
   }
  )
 }
);

Dojo

Dojo 不仅仅是下列示例中演示的简单 Ajax 请求/DOM 操作。它实际上是为硬核应用程序开发而构建的。这就是说,以这种方式查看 API 仍然是值得期待的。

注意两个独立的 “Ajax” 函数:xhrGet 和 xhrPost。另外还要注意的是,这里使用了 Dojo JSON 实用函数来分析输入数据。下面 展示了一个 GET 示例。

一个 Dojo GET 请求

var callback = function( data ) {
//note the document.getelementById alias
 dojo.byId("main").innerHTML += "<p>"+ data.sample.txt +"</p>";
}
var getData = function(){
//xhrGet is for get requests
dojo.xhrGet({
 //the URL of the request
 url: "_assets/data/json-1.json",
 //Handle the result as JSON data
 handleAs: "json",
 //The success handler
 load: callback
});
}
// Use connect to attach events
dojo.connect( dojo.byId("activate"), "onclick", getData );

下面展示了一个 Dojo POST,包含一个错误句柄的配置。

Dojo POST

var myMessages = {
 positive : "Today is a good day",
 negative : "Today stinks",
 meh : "meh"
}
var callback = function( data ) {
 dojo.byId("main").innerHTML += "<p>"+ data.positive +"</p>";
}
var errorHandler = function(){
 throw new Error("We dun goofed.")
}
var postData = function(){
 //not surprisingly xhrPost is for POST
 dojo.xhrPost({
  // The URL of the request
  url: "_assets/data/post-responder.do",
  //This will be JSON
  handleAs: "json",
  //Set the headers properly
  headers: { "Content-Type": "application/json; charset=uft-8"},
  //Use Dojo's JSON utility
  postData: dojo.toJson(myMessages),
  // The success handler
  load: callback,
  // The error handler
  error: errorHandler
 });
}
// Use connect to attach events
dojo.connect( dojo.byId("activate"), "onclick", postData );

Yahoo! 用户界面 (YUI)

YUI 库提供一个与前面两个略有不同的模式。首先,YUI 返回整个 XHR 对象,不仅解析数据,还允许更准确地操作返回数据和整个请求的可见性。这也意味着开发人员需要了解 XHR 对象的来龙去脉。另外,这里还展示了 YUI 模块加载程序 use() 的使用,需要注意的是,即使与 Ajax 没有直接联系(除了加载 io 模块之外)。中有一个 YUI 模块列表,还有一个用作参数的回调函数。一旦运行,就可以从 Yahoo! Content Delivery Network (CDN) 下载数据包,Yahoo! Content Delivery Network (CDN) 包含单个基于 CDN 的下载包中所需的所有模块。

一个 YUI GET 请求

// Create a new YUI instance and populate it with the required modules.
YUI().use('node','event', 'json', 'io', function (Y) {
 var callback = function( id, xhr ) {
  var data = Y.JSON.parse(xhr.responseText);
  Y.one('#main').append("<p>" 
   + data.sample.txt 
   +"</p>");
 }
 Y.one("#activate").on('click',
  function(){
   Y.io( '_assets/data/json-1.json', {
   //This is actually the default
   method: 'get',
   on:  {success: callback}
   })
  } 
 )
});

下面中的 POST 示例中呈现的一个有趣的样式风格将所有响应函数进一步分割成 on 对象。

YUI POST

YUI().use('node','event', 'json', 'io', function (Y) {
 var myMessages = {
  positive : "Today is a good day",
  negative : "Today stinks",
  meh : "meh"
 } 
 var callback = function( id, xhr ) {
  var data = Y.JSON.parse(xhr.responseText);
  Y.one('#main').append("<p>" 
   + data.positive 
   +"</p>");
 }
 var errorHandler = function( id, xhr){
  throw new Error("There was an error. The error status was " 
   + xhr.statusText 
   +".")
 }
 Y.one("#activate").on('click',
  function(){
   Y.io( '_assets/data/post-responder.do', {
   method: 'post',
   //Use the Y.JSON utility to convert messages to a string
   data : Y.JSON.stringify(myMessages),
   //All response methods are encapsulated in
   //the on object
   on:  {success: callback,
   failure: errorHandler }
   })
  } 
 )
});

正如您所看到的,基本模式在多数清单中都是一样的。除了支持 ActiveX 控件和 JSONP 示例之外,它们基本上基于同一原理,只是在核心 JavaScript 交互的顶层具有不同的 API 变化。

请注意,除了这里列出的基本交互之外,所有这些库还提供大量特性。尽管您可以做的大多数 Ajax 工作可以通过简单的 GET 和 POST 请求来处理,但让自己熟悉所选择的库中的高级特性非常有用。

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

推荐阅读:

用history让ajax支持前进/后退/刷新

使用Ajax时出现乱码怎么解决

The above is the detailed content of A brief history and basic usage of Ajax. 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