Home > Article > Web Front-end > A brief analysis of Ajax syntax
Ajax is a very common technology at present, and it is also a technology worthy of discussion and research. This article will focus on the development process of Ajax and combine it in different librariesframework Let’s share with you the new and old syntax of Ajax by using it.
##. # 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. For more information about Ajax, please go to PHP Chinese. Learn more about it online:
Native Ajax
Initiating and processing Ajax requests 1. Obtain the XMLHttpRequest object
var xhr = new XMLHttpRequest(); // 获取浏览器内置的XMLHttpRequest对象
var xhr; if (window.XMLHttpRequest) { xhr=new XMLHttpRequest(); } else if (window.ActiveXObject) { // 兼容老版本浏览器 xhr=new ActiveXObject("Microsoft.XMLHTTP"); }
2. Parameter configuration
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/'路径发送异步请求 }
The open method creates a new http request for us, where the first parameter is the request method. Generally 'GET' or 'POST'; the second parameter is the request url; the third parameter is whether it is asynchronous, the default is true
3. Send the request
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方法发送请求 }
What needs to be noted here is that if you use the GET method to pass parameters, we can directly put the parameters 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');
It will eventually be 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, our final transmission form will be like this :
Obviously this is not the data format expected by the server. We can write it like this:
xhr.open('POST', '/test/', true); xhr.send(JSON.stringify({name: 'luozh', size: 12}));
The final transmission format is as follows:
In this way, we can directly pass JSON
stringto the background for processing. Of course, the background may be configured accordingly. 4. Monitoring status
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('执行出错'); } } } }
Above we use onreadystatechange to monitor the state, and internally use readyState 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 codethrough 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('执行出错'); } }
However, it should be noted that IE has The support for the onload attribute
is not friendly.In addition to onload, there are also
onloadstart##onprogress
onabort
ontimeout
onerror
onloadend
等事件,有兴趣的同学可以亲自去实践它们的用处。
以上便是原生Ajax请求数据的常见代码。
jQuery作为一个使用人数最多的库,其Ajax很好的封装了原生Ajax的代码,在兼容性和易用性方面都做了很大的提高,让Ajax的调用变得非常简单。下面便是一段简单的jQuery的Ajax代码:
$.ajax({ method: 'GET', // 1.9.0本版前用'type' url: "/test/", dataType: 'json' }) .done(function() { console.log('执行成功'); }) .fail(function() { console.log('执行出错'); })
与原生Ajax不同的是,jQuery中默认的Content-type是'application/x-www-form-urlencoded; charset=UTF-8', 想了解更多的jQuery Ajax的信息可以移步官方文档:http://api.jquery.com/jquery.ajax
Vue.js作为目前热门的前端框架,其实其本身并不包含Ajax功能,而是通过插件的形式额外需要在项目中引用,其官方推荐Ajax插件为vue-resource,下面便是vue-resource的请求代码:
Vue.http.get('/test/').then((response) => { console.log('执行成功'); }, (response) => { console.log('执行出错'); });
vue-resource支持Promise API,同时支持目前的Firefox, Chrome, Safari, Opera 和 IE9+浏览器,在浏览器兼容性上不兼容IE8,毕竟Vue本身也不兼容IE8。想了解更多的vue-resource的信息可以移步github文档:https://github.com/vuejs/vue-resource
这里Angular.js中的Ajax主要指Angular的1.×版本,因为Angular2目前还不建议在生产环境中使用。
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('执行出错'); }); }]);
在Angular中,我们需要在控制器上注册一个$http的事件,然后才能在内部执行Ajax。Angular的Ajax默认的Content-type是'application/json;charset=UTF-8',所以如果想用表单的方式提交还需设置下headers属性。想了解更多的Angular Ajax的信息可以移步官方文档:https://docs.angularjs.org/api/ng/service/$http(可能需要翻墙)更多精彩内容关注微信公众号:全栈开发者中心(admin10000_com)
在React中我比较推荐使用fetch来请求数据,当然其不仅适用于React,在任何一种框架如上面的Vue、Angular中都可以使用,因为其已经被目前主流浏览器所支持,至于其主要功能和用法,我在下面会做下讲解。
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('执行出错'); });
可以看出使用Fetch后我们的代码更加简洁和语义化,链式调用的方式也使其更加流畅和清晰。随着浏览器内核的不断完善,今后的XMLHttpRequest会逐渐被Fetch替代。关于Fetch的详细介绍可以移步:https://segmentfault.com/a/1190000003810652
介绍了各种各样的Ajax API,我们不能避免的一个重要问题就是跨域,这里重点讲解下Ajax跨域的处理方式。
处理Ajax跨域问题主要有以下4种方式:
利用iframe
利用JSONP
利用代理
利用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');
以上的*号可以替换成允许访问的域名,*表示所有域名都可以访问。
It can be seen that the third and fourth methods are mainly background work, and the front end only needs to call it.
No matter how varied the syntax of Ajax is, no matter how libraries and frameworks encapsulate Ajax, it is just a tool to achieve asynchronous data interaction. We only need to understand the implementation of Ajax in native JS By understanding the concepts and processes of XMLHttpRequest and promise, you can easily navigate the era of asynchronous data interaction.
The above is the detailed content of A brief analysis of Ajax syntax. For more information, please follow other related articles on the PHP Chinese website!