简体   繁体   中英

Data fetched from JSON not getting updated

Below is the script:

$(document).ready(function () {
    $.getJSON('table.json', function (data) {
        $('#mytable').empty();
        var html = '';
        html += '<tr class="tableheader"><th>Name</th><th>Code</th><th>Value</th><th>Bid</th><th>Offer</th></tr>';
        for (var i = 0, size = data.length; i < size; i++) {
            html += '<tr class="tablecontent"><td>' + data[i].name + '</td><td>' + data[i].code + '</td><td>' + data[i].value + '</td><td>' + data[i].bid + '</td><td>' + data[i].offer + '</td></tr>';
        }
        $('#mytable').append(html);
        tablerows('mytable');
        setTimeout(poll, 5000);
    });
});
var poll = function () {
    alert("poll");
    $.getJSON('dummy.json', function (data) {
        setTimeout(poll, 5000);
    });
}

I want to update my data. The poll function is getting called after every 5 seconds which I checked through the alert . But data is not getting updated. Please tell me what I am doing wrong.

getJSON is a GET request so it will be cached. Set the proper no cache headers on the server.

Also look at your code, you are never processing the data

var poll = function () {
    alert("poll");
    $.getJSON('dummy.json', function (data) {
        setTimeout(poll, 5000);  //<--where is the processing you do nothing with the response???
    });
} 
$(document).ready(function() {
       // make the initial JSON request
    $.getJSON('table.json', init)
});

function poll() {
       // make the subsequent JSON requests
    $.getJSON('dummy.json', update);
}

function init(data) {
    $('#mytable').empty();
    var html = '';
    html += '<tr class="tableheader"><th>Name</th><th>Code</th><th>Value</th><th>Bid</th><th>Offer</th></tr>';
    for (var i = 0, size = data.length; i < size; i++) {
        html += '<tr class="tablecontent"><td>' + data[i].name + '</td><td>' + data[i].code + '</td><td>' + data[i].value + '</td><td>' + data[i].bid + '</td><td>' + data[i].offer + '</td></tr>';
    }
    $('#mytable').append(html);
    tablerows('mytable');
    setTimeout(poll, 5000);
}

function update(data) {
    var rows = $("#mytable tr.tablecontent").toArray();
    for (var i = 0, size = data.length; i < size; i++) {
        if (rows[i])
            rows[i].cells[3].firstChild.data = data[i].bid;
    }
    setTimeout(poll, 5000);
}

Here's the update function with more jQuery:

function update(data) {
    $("#mytable tr.tablecontent > td:nth-child(4)")
         .slice(0, data.length)
         .text(function(i) {
             return data[i].bid;
          });
    setTimeout(poll, 5000);
}

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