Use JSON data outside of initial .ajax call - Acce

2019-07-15 03:04发布

问题:

This is partly an extension to a Previous Question of mine:

I can now successfully returned JSON data from my CI controller which returns:

{"results":[{"id":"1","Source":"My Source","Title":"My Title". . . .

The Controller:

function outputAjax()
{
    $this->load->model('my_model');
    $data['results'] = $this->site_model->getInfo();
    $this->output->set_output(json_encode($data));
}

This is my current script I am using to retrieve the .ajax request:

$(document).ready(function()
        {    
            $.ajax(
            {
                url: 'http://localhost/project/index.php/controller/outputAjax',
                dataType:'json',
                success: function(data) 
                {   
                    var limit = 19; //how many json objects are needed initially
                    var arr = []; // item.id of objects that have been used 
                    $.each(data.results, function(index,item)
                    {
                        if (index > limit) return false; // gets required initial json objects
                        arr.push(item.id); // stores used json objects id's

                        // whole bunch of checks on item.id , item.Title, item.Description, etc...

                        $("#masonry-content").append('<div class="item" ' + item.id + item.Title + ' ... </div>');
                    });

As the above code shows, I am currently taking the first 20 objects of JSON data and appending them to the page container. This works fine but..

The issue I am having is that I would like to update the content in those 20 divs that have been appended to the page on a time interval with other objects of the initially returned JSON data. I feel like the best way to do this is to layout the div's statically on the page since there will always be the same amount and then just update the data in those divs accordingly.

My question is how can I still access the returned JSON data once outside the scope of the initial .ajax call.

For example: If I would leave the script setup the way it is, after I make the initial .ajax call and append() the content to the container with the first 20 JSON data objects ( item ). How do I access the rest of the objects in the JSON data?

I already assumed my best bet to keep track of the objects returned was to store the item.id of each object in an array arr[ ] Please correct me if this does not make sense or their is a much easier way. But, I still don't know how to access the leftover JSON data objects?

I feel as though I am missing something obvious such as making my javascript more object oriented would help so then I could access each json object individually and perform different functions on it but I feel as though I may be lost a little.

回答1:

I think you can just store your json in a global variable, and loop through the items as you need them, starting with 20 by calling setDivs(20) after successfully loading the json.

// Declaration of global variables
data = ''; // JSON data will be stored here
myurl = 'http://localhost/project/index.php/controller/outputAjax';
index = 0;

$(document).ready(function () {
    $.getJSON(myurl, function (JSON) { data = JSON; setDivs(20); });
    $('#next20').click(function() { setDivs(20); });
});

function setDivs(num) {
    $("#masonry-content").empty();
    for (var i = index ; i < index + num -1; i++) {
        $("#masonry-content").append('<div class="item" ' + data["results"][i].id + data["results"][i].Title + ' ... </div>');
    }
    index += num;
}

I've also added code which will update your #masonry-content element with the next 20 divs from the json object upon clicking a #next20 element on the page.

Of course, I've no idea if your #masonry-content element is empty to begin with. If it's not, then add something like a <div id="json-data"></div> inside your #masonry-content element, and update the above code accordingly by replacing both instances of $('#masonry-content") with $('#json-data')

If data["results"][i] doesn't work, maybe try data.results[i].

If you are using Chrome, pull up the console (CTRL+SHIFT+J) and type data and press enter. If the JSON was successfully loaded, you should be able to explore the tree of the data object. Then you can play around with it in the console, trying data["results"], data.results etc. and keep working your way down (i.e. try data["results"][0] and verify that it pulls the first item).

Update:

Here's a working JSON/AJAX Ticker example which randomly swaps items every 4.5 seconds. It was built in response to twhyler's follow-up question on stackoverflow.



回答2:

You could, simply declare a variable outside of your ajax call then inside your ajax function the update the variables value to the json object in its entirety. See below I named the variable data

$(document).ready(function()
        {

         var data = '';

            $.ajax(
            {
                url: 'http://localhost/project/index.php/controller/outputAjax',
                dataType:'json',
                success: function(data) 
                {   

                    data = data;

                    });

However I would personally create a template div of how you want an individual element to appear and then just fill in the data rather than trying to search specific tags in 20 places and then replacing that data with new data. I think it would be much easier and efficient to basically empty $("#masonry-content").empty(); Then refill it with the new elements using append or something like that.