简体   繁体   中英

how do you do ajax call in javascript

I am building a dashboard that will have buttons on top for monthly, weekly and real time data.

<div class="zoom_controls"> 
                              <a class="profile" id="monthly_data" href="#" data-chart="line" data-range="6m">Monthly</a>
                              <a class="profile" id="weekly_data"href="#" data-chart="line" data-range="3m">Weekly</a>
                              <a class="profile" id="real_time" href="#" data-chart="line" data-range="1m">Real Time</a>
</div>
<div class="main" id="chart" style="width:700px; height:300px;"></div>

This is the javascript that calls a php file to get the data and insert it into highcharts:

function cpu_current() {
                //current_cpu_data.php retrieves the data from a flat file
        $.getJSON('current_cpu_data.php', function(data) {
        var chart = new Highcharts.StockChart({
         chart: {
                borderColor: '#98AFC7',
                borderRadius: 20,
                borderWidth: 1,
                renderTo: 'chart',
                type: 'line',
                marginRight: 10,
                zoomType: 'x'
            },

            exporting: {
            enabled: true
        },
           legend: {
            enabled: true,
            backgroundColor: '#FCFFC5',
            borderColor: 'black',
            borderWidth: 2,
            width: 500,
            shadow: true
        },
        plotOptions: {
            series: {
                lineWidth:1
            }
        },
            rangeSelector: {
                enabled:false              
            },

            scrollbar: {
                    enabled: false
                    },
            navigator : {
                enabled : false
            },
            xAxis: {
                gridLineColor: '#EEEEEE',
                gridLineWidth: 1
            },
            yAxis: { // Primary yAxis
                labels: {

                    style: {
                        color: 'blue'
                    }
                },
                gridLineColor: '#EEEEEE',
                gridLineWidth: 0,
                tickInterval: 20,
                min:0,
                max:100,
                plotLines : [{
                    value : 70,
                    color : '#FF3300',
                    dashStyle : 'line',
                    width : 1,
                    label : {
                        text : 'Threshold=70%',
                        align: 'right',
                        style: {
                        fontWeight: 'bold'
                        }
                    }
                }],
                title: {
                    text: '% CPU Utilization',
                    style: {
                        color: 'blue'
                    }
                }
            },

            credits: {
                enabled: false
            },

            title: {
                text: 'CPU',
                style: {
                    color: '#333000',
                    fontSize: '14px'
                }
            },
            subtitle: {
                text: '10 minute peaks in last 24 hours'
                },

            tooltip: {
                pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y} </b><br>',
                valueDecimals: 2
            },
            series:data

    });
    });
}

Here I can use jquery click event to switch between different tabs:

$("#monthly_data").click(function() {
        hmms_cpu_current();
    });
    $("#weekly_data").click(function() {
        hmms_cpu_weekly();
    });
    $("#real_time").click(function() {
        cpu_current();
    });

My question is this, when the user only interested in real_time and clicks and leaves it there, I need cpu_current() to update on its own via ajax calls. If a user clicks on monthly_data and leaves it there cpu_current() need to stop.

How would do this given the above code?

if you are using MVC Model you can use Ajax like this using onclick method of particular javascript function ,

<script type="text/javascript">
  function hmms_cpu_current() {
    $.ajax({
        type: 'GET',
        async: false,
        url: 'yourcontroller/youraction',
        contentType: "application/json; charset=utf-8",
        dataType: 'json',
        success: function (data) {
            var obj = $.parseJSON(data);

            $.each(data, function (i, item) {

                alert(item.text) // do your stuff with returned value
            });


        },
        error: function () {
            output.text('There was an error loading the data.');
        }
    });
}

I would add a Javascript Timer() or setTimeout() which re-sends the ajax call and updated the page.

You could also give the user the option of doing this and put it inside a Function.

If you give the Timer an ID, you can also stop and start it.

Modify all your functions to return a jqXHR like this:

function cpu_current() {
                //$.getJSON return jqXHR, you could use it to abort ajax.
       return $.getJSON('current_cpu_data.php', function(data) {
              //All your code
}

The use abort in your event handlers:

var currentjqXHR;

    $("#monthly_data").click(function() {
            if (currentjqXHR){
               currentjqXHR.abort();//abort current ajax
            }
            currentjqXHR = hmms_cpu_current();
        });
        $("#weekly_data").click(function() {
            if (currentjqXHR){
               currentjqXHR.abort();//abort current ajax
            }
            currentjqXHR  = hmms_cpu_weekly();
        });
        $("#real_time").click(function() {
            if (currentjqXHR){
               currentjqXHR.abort();//abort current ajax
            }
            currentjqXHR  = cpu_current();
        });

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