How to determine if the `.post` request has been started and finish in jquery

回眸只為那壹抹淺笑 提交于 2020-01-03 04:27:25

问题


Is there a way on how I can determine if the .post request has started and finished.

I mean, if i have a code:

$.post('address.php', { value: value }, function(data) {
    alert(data);    
});

How can I know it was started for me to show the loading image and hide that loading image upon completion of the said .post request.

I know there is a way on how to make this done because, most websites are using this kind of algorithm. And I want to write it in jQuery.

Any inputs?


回答1:


AJAX requests are always started immediately, so you need to know only when it has finished. Your loader can be shown right before sending the request.

One of the better ways of doing it is the following, if you need to know whether it has succeeded or failed.

// Show your loader image
$("#loader").show();

$.post("address.php", {
    value: value
}).done(function() {
    // Only on success (HTTP status code < 400)
    alert("Success!");
}).fail(function() {
    // Only on errors (HTTP status code >= 400)
    alert("Error :(");
}).always(function() {
    // Hide your loader image.
    // Will always happen, after .done()/.fail() were fired.
    $("#loader").hide();
});



回答2:


The request is initiated immediately, so you can show the loader just before you call $.post().

Calling $.post() will return a promise, so you can do something like this:

// Show your loader
$("#myloader").show()

$.post('address.php', { value: value }, function(data) {
    alert(data);
})
.always(function() { 
    // Hide it again when the request is complete
    $("#myloader").hide();
});

This is documented in the jQuery API documentation of $.post().




回答3:


If you use $.ajax instead of $.post ( $.post is just a shorthand Ajax function anyway ) you can use the beforeSend and complete callbacks ( or the success callback - although if there is an error this callback may not execute ) to contain the logic of displaying and hiding your loading icon to within the ajax call itself, an example of this would be:

$.ajax({
    type: 'POST',
    data: { value : value },
    url : 'address.php',
    beforeSend : function() { 
        $("#myloader").show(); 
    },
    complete : function() { 
        $("#myloader").hide(); 
    },
    success : function(data) {
        console.log('success');
    }
});

And here is the link to the Ajax section of the jQuery docs so you can read in more detail about the callbacks and other options available. http://api.jquery.com/jQuery.ajax/



来源:https://stackoverflow.com/questions/17719289/how-to-determine-if-the-post-request-has-been-started-and-finish-in-jquery

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!