jQuery AJAX polling for JSON response, handling based on AJAX result or JSON content

前端 未结 4 605
萌比男神i
萌比男神i 2020-11-29 16:49

I\'m a novice-to-intermediate JavaScript/jQuery programmer, so concrete/executable examples would be very much appreciated.

My project requires using AJAX to poll a

4条回答
  •  余生分开走
    2020-11-29 17:31

    Off the top of my head:

    $(function ()
    {
        // reference cache to speed up the process of querying for the status element
        var statusElement = $("#status");
    
        // this function will run each 1000 ms until stopped with clearInterval()
        var i = setInterval(function ()
        {
            $.ajax(
            {
                success: function (json)
                {
                    // progress from 1-100
                    statusElement.text(json.progress + "%");
    
                    // when the worker process is done (reached 100%), stop execution
                    if (json.progress == 100) i.clearInterval();
                },
    
                error: function ()
                {
                    // on error, stop execution
                    i.clearInterval();
                }
            });
        }, 1000);
    });
    

提交回复
热议问题