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.
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 and interact with data 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. For more introduction to Ajax, please go to W3School to learn: http://www.php.cn/
Basically all modern browsers support native Ajax. Function, let’s introduce in detail how we use native JS to initiate and process Ajax requests.
var xhr = new XMLHttpRequest(); // 获取浏览器内置的XMLHttpRequest对象
If your project application does not consider lower versions of IE, you can directly use the above method for all modern browsers (Firefox, Chrome, Safari and Opera) All 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"); }
With the XMLHttpRequest object, we also need to configure some request parameter information. To complete data interaction, 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/'路径发送异步请求 }
The open method creates a new http request for us, where the first parameter is the request method, usually 'GET' or 'POST'; the second The first parameter is the request URL; the third parameter is whether it is asynchronous, and the default is true.
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方法发送请求 }
What needs to be noted here is that if the GET method is used 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 use the Content-Type of 'text/plain;charset=UTF-8' by default To send data, if we write it 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}));
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('执行出错'); } } } }
xhr.onload = function () { // 调用onload if (xhr.status === 200) { // status为200表示请求成功 console.log('执行成功'); } else { console.log('执行出错'); } }
$.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://www.php.cn/
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文档:http://www.php.cn/
这里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的信息可以移步官方文档:http://www.php.cn/$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的详细介绍可以移步:http://www.php.cn/
介绍了各种各样的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');Copy after login
以上的*号可以替换成允许访问的域名,*表示所有域名都可以访问。
由此可见,第3和第4种方式主要是后台的活,前端只需调用就可以。
总结
无论Ajax的语法多么多变,无论库和框架如何封装Ajax,其只是一种实现异步数据交互的工具,我们只需理解原生JS中Ajax的实现原理,了解XMLHttpRequest及promise的概念和流程,便可以轻松的在数据异步交互的时代游刃有余。
以上就是Ajax语法浅析的内容,更多相关内容请关注PHP中文网(www.php.cn)!