Home  >  Article  >  Web Front-end  >  A brief analysis of Ajax syntax

A brief analysis of Ajax syntax

黄舟
黄舟Original
2017-02-22 11:33:401229browse

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 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/

Native Ajax

Basically all modern browsers support native Ajax. Function, let’s introduce in detail how we use native JS to initiate and process Ajax requests.

 1. Get the XMLHttpRequest object

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");
}

 2. Parameter configuration

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.

 3. Send a 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方法发送请求
}

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}));

The final transmission format is as follows:

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

4. 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('执行出错');
            }   
        }
    }
}

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 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('执行出错');
    }   
}

However, it should be noted that IE The support for the onload attribute is not friendly.

In addition to onload, there are also

  • onloadstart

  • ##onprogress
  • onabort
  • ontimeout
  • onerror
  • ##onloadend
  • 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

1. Ajax in jQuery

As the library with the most users, jQuery’s Ajax encapsulates the native Ajax code well. , which has made great improvements 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('执行出错');
})

  与原生Ajax不同的是,jQuery中默认的Content-type是'application/x-www-form-urlencoded; charset=UTF-8', 想了解更多的jQuery Ajax的信息可以移步官方文档:http://www.php.cn/

  2.Vue.js中的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文档:http://www.php.cn/

  3.Angular.js中的Ajax

  这里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)

  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('执行出错');
});

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

 跨域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');


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

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

 总结

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

以上就是Ajax语法浅析的内容,更多相关内容请关注PHP中文网(www.php.cn)!


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