Parallel Ajax Calls in Javascript/jQuery

前端 未结 9 1682
感情败类
感情败类 2021-02-07 17:18

I am completely new to Javascript/jquery world and need some help. Right now, I am writing one html page where I have to make 5 different Ajax calls to get the data to plot grap

相关标签:
9条回答
  • 2021-02-07 17:54

    You can't do that using async: false - the code executes synchronously, as you already know (i.e. an operation won't start until the previous one has finished).
    You will want to set async: true (or just omit it - by default it's true). Then define a callback function for each AJAX call. Inside each callback, add the received data to an array. Then, check whether all the data has been loaded (arrayOfJsonObjects.length == 5). If it has, call a function to do whatever you want with the data.

    0 讨论(0)
  • 2021-02-07 17:55

    Using jQuery.when (deferreds):

    $.when( $.ajax("/req1"), $.ajax("/req2"), $.ajax("/req3") ).then(function(resp1, resp2, resp3){ 
        // plot graph using data from resp1, resp2 & resp3 
    });
    

    callback function only called when all 3 ajax calls are completed.

    0 讨论(0)
  • 2021-02-07 17:55

    Here's a solution to your issue: http://jsfiddle.net/YZuD9/

    0 讨论(0)
  • 2021-02-07 17:59

    You won't be able to handle it like your example. Setting to async uses another thread to make the request on and lets your application continue.

    In this case you should utilize a new function that will plot an area out, then use the callback functions of the ajax request to pass the data to that function.

    For example:

    $(document).ready(function() {
        function plotArea(data, status, jqXHR) {
          // access the graph object and apply the data.
          var area_data = $.parseJSON(data);
        }
    
        $.ajax({
            url : url0,
            async : false,
            dataType : 'json',
            success: poltArea
        });
    
        $.ajax({
            url : url1,
            async : false,
            dataType : 'json',
            success: poltArea
        });
    
        $.ajax({
            url : url4,
            async : false,
            dataType : 'json',
            success: poltArea
        });
    
        // some code for generating graphs
    
    }); // closing the document ready function 
    
    0 讨论(0)
  • 2021-02-07 18:00

    Let's try to do it in this way:

    <script type="text/javascript" charset="utf-8">
        $(document).ready(function() {
            var area0Obj = {responseText:''};
            var area1Obj = {responseText:''};
            var area2Obj = {responseText:''};
    
            var url0 = 'http://someurl/url0/';
            var url1 = 'http://someurl/url1/';
            var url2 = 'http://someurl/url2/';
    
            var getData = function(someURL, place) {
                $.ajax({
                    type     : 'POST',
                    dataType : 'json',
                    url      : someURL,
                    success  : function(data) {
                        place.responseText = data;
                        console.log(place);
                    }
                });
            }
    
            getData(url0, area0Obj);
            getData(url1, area1Obj);
            getData(url2, area2Obj);
    
        }); 
    </script>
    

    if server side will be smth. like this:

    public function url0() {
        $answer = array(
            array('smth' => 1, 'ope' => 'one'),
            array('smth' => 8, 'ope' => 'two'),
            array('smth' => 5, 'ope' => 'three')
        );
        die(json_encode($answer));
    }
    
    public function url1() {
        $answer = array('one','two','three');
        die(json_encode($answer));
    }
    
    public function url2() {
        $answer = 'one ,two, three';
        die(json_encode($answer));
    }
    

    So there, as you can see, created one function getData() for getting data from server and than it called 3 times. Results will be received in asynchronous way so, for example, first can get answer for third call and last for first call.

    Console answer will be:

    [{"smth":1,"ope":"one"},{"smth":8,"ope":"two"},{"smth":5,"ope":"three"}]
    
    ["one","two","three"]
    
    "one ,two, three"
    

    PS. please read this: http://api.jquery.com/jQuery.ajax/ there you can clearly see info about async. There default async param value = true.

    By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false. Cross-domain requests and dataType: "jsonp" requests do not support synchronous operation. Note that synchronous requests may temporarily lock the browser, disabling any actions while the request is active...

    0 讨论(0)
  • 2021-02-07 18:00

    In jQuery.ajax you should provide a callback method as below:

    j.ajax({
            url : url0,
            async : true,
            dataType : 'json',
            success:function(data){
                 console.log(data);
            }
        }
    

    or you can directly use

    jQuery.getJSON(url0, function(data){
      console.log(data);
    });
    

    reference

    0 讨论(0)
提交回复
热议问题