Home  >  Article  >  Web Front-end  >  Synchronous request between $http and ajax (code example)

Synchronous request between $http and ajax (code example)

云罗郡主
云罗郡主forward
2018-10-17 14:11:454064browse

The content this article brings to you is about the synchronization request (code example) of $http and ajax. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

In web front-end development, although asynchronous network requests are generally used to solve most functional requirements, in the case of some specific needs, we still have to use synchronous network requests to solve some special problems. need. So this article introduces how to implement synchronous network requests using $http in AngularJS and ajax in jQuery.

(1) $http synchronous network request

In fact, this implementation is very simple. The important thing lies in two points: the first point is to directly return the result in the successful callback method. ; The second point is that $http itself returns the promise object directly after execution. By meeting these two requirements, the synchronization of $http can be achieved.

The result set obtained by the final network request is in the returned promise object.

Template code implementation:

 let requestConfig = {
            url:"...",
            method:"post"
        };
        let promise = $http(requestConfig).then(function (response) {
            return response;
        });
        console.log("结果在promise对象中",promise);

(2) Ajax synchronous network request

To realize the synchronous network execution of ajax, two points are also important: The first point is to configure the value of async to false in the request parameters; the second point is not to write the success or failure callback method of ajax, but directly return the result set obtained after the ajax execution. By meeting these two requirements, you can achieve synchronous implementation of ajax.

Template code implementation:

 let result = $.ajax({
            url:"...",
            type:"get",
            async:false
        });
        console.log("返回结果直接是result",result);

The above is the complete introduction to the synchronization request (code example) of $http and ajax, if you want to know more about HTML video Tutorial , please pay attention to the PHP Chinese website.

The above is the detailed content of Synchronous request between $http and ajax (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete