Parallel Ajax Calls in Javascript/jQuery

前端 未结 9 1686
感情败类
感情败类 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 18:02

    The following worked for me - I had multiple ajax calls with the need to pass a serialised object:

        var args1 = {
            "table": "users",
            "order": " ORDER BY id DESC ",
            "local_domain":""
        }
        var args2 = {
            "table": "parts",
            "order": " ORDER BY date DESC ",
            "local_domain":""
        }
    
        $.when(
            $.ajax({
                    url: args1.local_domain + '/my/restful',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },
                    type: "POST",
                    dataType : "json",
                    contentType: "application/json; charset=utf-8",
                    data : JSON.stringify(args1),
                    error: function(err1) {
                        alert('(Call 1)An error just happened...' + JSON.stringify(err1));
                    }
                }),
            $.ajax({
                url: args2.local_domain + '/my/restful',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                type: "POST",
                dataType : "json",
                contentType: "application/json; charset=utf-8",
                data : JSON.stringify(args2),
                error: function(err2) {
                    calert('(Call 2)An error just happened...' + JSON.stringify(err2));
                }
            })                     
    
        ).then(function( data1, data2 ) {
            data1 = cleanDataString(data1);
            data2 = cleanDataString(data2);
    
            data1.forEach(function(e){
                console.log("ids" + e.id)
            });
            data2.forEach(function(e){
                console.log("dates" + e.date)
            });
    
        })
    
        function cleanDataString(data){
                data = decodeURIComponent(data);
                // next if statement was only used because I got additional object on the back of my JSON object
                // parsed it out while serialised and then added back closing 2 brackets
                if(data !== undefined && data.toString().includes('}],success,')){ 
                    temp = data.toString().split('}],success,');
                    data = temp[0] + '}]';
                }
                data = JSON.parse(data);
                return data;                    // return parsed object
          }
    

提交回复
热议问题