Home > Web Front-end > JS Tutorial > What is the common syntax of AJAX

What is the common syntax of AJAX

php中世界最好的语言
Release: 2017-12-02 09:48:02
Original
1979 people have browsed it

We all know that ajax is now a very common technology. This article mainly introduces the implementation principle of ajax in native JS and the concepts and processes of XMLHttpRequest and promise.

Ajax is a very common technology at present, and it is also a technology worthy of discussion and research. This article will share with you the new and old syntax of Ajax based on the development process of Ajax and how it is used in different library frameworks.

Introduction to Ajax

The full name of Ajax is "Asynchronous Javascript And XML", which means "asynchronous JavaScript and XML". Through Ajax, we can send requests to the server for data interaction without blocking the page, which can also be understood as asynchronous data transmission. With the help of Ajax, our web page only needs to be partially refreshed to update the display of data, reducing the amount of unnecessary data, greatly improving the user experience, shortening the user's waiting time, and making the web application smaller and faster. More friendly.

Of course, the above are commonplace content. As a qualified developer, you are basically familiar with it. Here is just a brief introduction for those who are just getting started.

Native Ajax

Basically all modern browsers support the native Ajax function. Here is a detailed introduction to how we use native JS to initiate and process Ajax requests.

Get the XMLHttpRequest object

var xhr = new XMLHttpRequest(); // Get the browser's built-in XMLHttpRequest object

If your project application does not consider lower versions of IE, then You can use the above method directly. All modern browsers (Firefox, Chrome, Safari and Opera) have built-in XMLHttpRequest objects. If you need to be compatible with older versions of IE (IE5, IE6), you can use ActiveX objects:

var xhr;
if (window.XMLHttpRequest) {
  xhr=new XMLHttpRequest();
} else if (window.ActiveXObject) {  // 兼容老版本浏览器
  xhr=new ActiveXObject("Microsoft.XMLHTTP");
}
Copy after login

Parameter configuration

With the XMLHttpRequest object, we also need to configure some request parameter information to complete the data To interact, just use the open method:

var xhr;
if (window.XMLHttpRequest) {
  xhr=new XMLHttpRequest();
} else if (window.ActiveXObject) {
  xhr=new ActiveXObject("Microsoft.XMLHTTP");
}
if (xhr) {
  xhr.open('GET', '/test/', true); // 以GET请求的方式向'/test/'路径发送异步请求
}
Copy after login

The open method creates a new http request for us, where the first parameter is the request method, usually 'GET' or 'POST'; the second parameter is the request URL; the third parameter is whether it is asynchronous, and the default is true.

Send request

After configuring the basic parameter information, we directly call the send method to send the request. The code is as follows:

var xhr;
if (window.XMLHttpRequest) {
  xhr=new XMLHttpRequest();
} else if (window.ActiveXObject) {
  xhr=new ActiveXObject("Microsoft.XMLHTTP");
}
if (xhr) {
  xhr.open('GET', '/test/', true); 
  xhr.send(); // 调用send方法发送请求
}
Copy after login

What needs to be noted here is that if the GET method is used to pass parameters, We can put the parameters directly after the url, such as '/test/?name=luozh&size=12'; if using the POST method, then our parameters need to be written in the send method, such as:

xhr.open('POST', '/test/', true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded"); // 将请求头设置为表单方式提交
xhr.send('name=luozh&size=12');
Copy after login

will eventually Passed in the form of Form Data:

If the request header is not set, native Ajax will send data using the Content-Type of 'text/plain;charset=UTF-8' by default. If written according to the above parameters The form, the form we finally transmit is like this:

Obviously this is not the data format expected by the server, we can write like this:

xhr.open('POST', '/test/', true);
xhr.send(JSON.stringify({name: 'luozh', size: 12}));
Copy after login

In this way we can directly pass the JSON string to the background processing, Of course, the background may be configured accordingly.

Monitoring status

After sending the Ajax request, we need to monitor the status returned by the server and process it accordingly. Here we need to use the onreadystatechange method, the code is as follows:

var xhr;
if (window.XMLHttpRequest) {
  xhr=new XMLHttpRequest();
} else if (window.ActiveXObject) {
  xhr=new ActiveXObject("Microsoft.XMLHTTP");
}
if (xhr) {
  xhr.open('GET', '/test/', true);   // 以GET请求的方式向'/test/'路径发送异步请求
  xhr.send();
  xhr.onreadystatechange = function () {  // 利用onreadystatechange监测状态
    if (xhr.readyState === 4) {  // readyState为4表示请求响应完成
      if (xhr.status === 200) {  // status为200表示请求成功
        console.log('执行成功');
      } else {
        console.log('执行出错');
      }  
    }
  }
}
Copy after login

Above we use onreadystatechange to monitor the state, and use readyState internally to obtain the current state. readyState has a total of 5 stages. When it is 4, it means that the response content has been parsed and can be called on the client. When readyState is 4, we obtain the status code through status. When the status code is 200, the success code is executed, otherwise the error code is executed.

Of course we can use onload to replace the situation where onreadystatechange is equal to 4, because onload is only called when the state is 4. The code is as follows

xhr.onload = function () {  // 调用onload
  if (xhr.status === 200) {  // status为200表示请求成功
    console.log('执行成功');
  } else {
    console.log('执行出错');
  }  
}
Copy after login

However, it should be noted that IE does not support onload Support for this property is not friendly.

In addition to onload, there are also:

1.onloadstart
2.onprogress
3.onabort
4.ontimeout
5.onerror
6.onloadend
Copy after login

and other events. Interested students can practice their usefulness in person.

The above is the common code for native Ajax request data.

Ajax in other library frameworks

Ajax in jQuery

jQuery is the library with the most users, and its Ajax is well encapsulated The native Ajax code has been greatly improved in terms of compatibility and ease of use, making Ajax calls very simple. The following is a simple jQuery Ajax code:

$.ajax({
  method: 'GET', // 1.9.0本版前用'type'
  url: "/test/",
  dataType: 'json'
})
.done(function() {
  console.log('执行成功');
})
.fail(function() {
  console.log('执行出错');
})
Copy after login

Unlike native Ajax, the default Content-type in jQuery is 'application/x-www-form-urlencoded; charset=UTF-8' , If you want to know more about jQuery Ajax, you can go to the official documentation: http://api.jquery.com/jquery.ajax/

Ajax

Vue in Vue.js. As a popular front-end framework, js itself does not actually contain Ajax functions. Instead, it needs to be referenced in the project in the form of plug-ins. The official recommended Ajax plug-in is vue-resource. The following is the request code of vue-resource:

Vue.http.get('/test/').then((response) => {
  console.log('执行成功');
}, (response) => {
  console.log('执行出错');
});
Copy after login

3.Ajax in Angular.js

The Ajax in Angular.js here mainly refers to the 1.× version of Angular, because Angular2 is not currently recommended for use in production environments.

var myApp = angular.module('myApp',[]);
var myCtrl = myApp.controller('myCtrl',['$scope','$http',function($scope, $http){
  $http({
    method: 'GET',
    url: '/test/',
    headers: {'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'} 
  }).success(function (data) {
    console.log('执行成功');
  }).error(function () {
    console.log('执行出错');
  });
}]);
Copy after login

在Angular中,我们需要在控制器上注册一个$http的事件,然后才能在内部执行Ajax。Angular的Ajax默认的Content-type是'application/json;charset=UTF-8',所以如果想用表单的方式提交还需设置下headers属性。

4.React中的Ajax

在React中我比较推荐使用fetch来请求数据,当然其不仅适用于React,在任何一种框架如上面的Vue、Angular中都可以使用,因为其已经被目前主流浏览器所支持,至于其主要功能和用法,我在下面会做下讲解。

Fetch API

Fetch API 是基于 Promise 设计,由于Promise的浏览器兼容性问题及Fetch API本身的兼容问题,一些浏览器暂时不支持Fetch API,浏览器兼容图如下:

当然我们可以通过使用一些插件来解决兼容性问题,比如:fetch-polyfill、es6-promise、fetch-ie8等。

使用Fetch我们可以非常便捷的编写Ajax请求,我们用原生的XMLHttpRequst对象和Fetch来比较一下:

XMLHttpRequst API
// XMLHttpRequst API
var xhr = new XMLHttpRequest();
xhr.open('GET', '/test/', true);
xhr.onload = function() {
  console.log('执行成功');
};
xhr.onerror = function() {
  console.log('执行出错');
};
xhr.send();
Fetch API 
fetch('/test/').then(function(response) {
  return response.json();
}).then(function(data) {
  console.log('执行成功');
}).catch(function(e) {
  console.log('执行出错');
});
Copy after login

可以看出使用Fetch后我们的代码更加简洁和语义化,链式调用的方式也使其更加流畅和清晰。随着浏览器内核的不断完善,今后的XMLHttpRequest会逐渐被Fetch替代。关于Fetch的详细介绍可以移步:https://segmentfault.com/a/1190000003810652

跨域Ajax

介绍了各种各样的Ajax API,我们不能避免的一个重要问题就是跨域,这里重点讲解下Ajax跨域的处理方式。

处理Ajax跨域问题主要有以下4种方式:

1.利用iframe

2.利用JSONP

3.利用代理

4.利用HTML5提供的XMLHttpRequest Level2

第1和第2种方式大家应该都非常熟悉,都属于前端的活,这里就不做介绍了,这里主要介绍第3和第4种方式。

利用代理的方式可以这样理解:

通过在同域名下的web服务器端创建一个代理:

北京服务器(域名:www.beijing.com)

上海服务器(域名:www.shanghai.com)

比如在北京的web服务器的后台(www.beijing.com/proxy-shanghaiservice.php)来调用上海服务器(www.shanghai.com/services.php)的服务,然后再把访问结果返回给前端,这样前端调用北京同域名的服务就和调用上海的服务效果相同了。

利用XMLHttpRequest Level2的方式需要后台将请求头进行相应配置:

// php语法
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET,POST');
Copy after login

以上的*号可以替换成允许访问的域名,*表示所有域名都可以访问。

由此可见,第3和第4种方式主要是后台的活,前端只需调用就可以。

总结

无论Ajax的语法多么多变,无论库和框架如何封装Ajax,其只是一种实现异步数据交互的工具,我们只需理解原生JS中Ajax的实现原理,了解XMLHttpRequest及promise的概念和流程,便可以轻松的在数据异步交互的时代游刃有余。


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

相关阅读:

CSS的文本字体颜色如何设置

css里的font文字怎么设置

 Css3中的transform 渐变属性怎么使用

The above is the detailed content of What is the common syntax of AJAX. 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