简体   繁体   中英

Consequtive Ajax Calls from HTML (and jQuery)

I am writing a reporting tool that allows users to check certain servers with a single click on their mouses.

Basically, I have a PHP script called check_server.php . This file needs 1 parameter, named serverNode. For example check_server.php?serverNode=1234 . This script returns either true or false. False means that the server is down.

Now, what I am trying to achieve is to have a simple 2-column table with all the server-nodes listed in the first column. When the user clicks "report", then I want to make a Ajax call for every row in the table. So, first check_server.php?serverNode=1 , then check_server.php?serverNode=5 etc. etc. Then a success or failed icon is shown for every row.

How can I do this? The next node may only be checked, if the previous one returns true of false. Does somebody have an (clear) example? Thanks in advance!

I don't know whether I understood your question rightly or not, but I am thinking that you are trying to send one ajax request after completing other ajax request. If that is right you can try this one.

Every ajax request will have some states like before, after, on complete etc..

Define your ajax request with one jQuery variable like

var xyz = $.ajax({
   ---
   ---
})

Now you can check like this

if( xyz.readyState == 1 ) { /* send other ajax request */ }

This automatically sends one more ajax request when first one completed.

Maybe you can have something like this (DISCLAIMER: I didn't test it):

var nodeIDs = [1, 2, 3, 5, 9, 10];

function checkNextNode() {
    // no more nodes to check
    if (nodeIDs.length === 0)
    {
        return;
    }

    // get first nodeId in the list
    var nextNode = nodeIDs.shift();

    // make an AJAX call to check this nodeID
    $.ajax({
        type: 'GET',
        url: 'check_server.php',
        data: { serverNode: nextNode },
        success: function onSuccess(result) {
            // if the AJAX call is a success, do something useful with result
            // ex: display it in the table 

            // then check the next node
            checkNextNode();
        }
    });
}

// when the user click on the "report" element, call the "checkNextNode" function
yourReportElement.on('click', checkNextNode);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM