在初始.ajax调用之外使用JSON数据 - 访问剩余的JSON数据 [英] Use JSON data outside of initial .ajax call - Access leftover JSON data

查看:103
本文介绍了在初始.ajax调用之外使用JSON数据 - 访问剩余的JSON数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这部分是对上一个问题的扩展

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

我现在可以从我的CI控制器成功返回JSON数据,返回:

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

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

控制器:

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

这是我用来检索 .ajax 请求:

$(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>');
                    });

如上面的代码所示,我目前正在获取JSON数据的前20个对象并将它们附加到页面容器。这样可以正常但是..

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..

我遇到的问题是我要更新已添加的20个div中的内容使用最初返回的JSON数据的其他对象到时间间隔上的页面。我觉得这样做的最好方法是在页面上静态布局div,因为总会有相同的数量,然后相应地更新这些div中的数据。

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.

我的问题是如何在初始.ajax调用范围之外仍然访问返回的JSON数据。

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

例如:如果我按原样保留脚本设置,在我创建初始 .ajax之后 call和 append()带有前20个JSON数据对象的容器内容( item )。如何访问JSON数据中的其余对象?

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?

我已经假设我最好的办法是跟踪返回的对象是存储item.id的数组中的每个对象 arr [] 请纠正我,如果这没有意义,或者他们是一个更简单的方法。但是,我仍然不喜欢我不知道如何访问剩余的JSON数据对象

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?

我觉得我错过了一些明显的东西,例如让我的javascript更多面向对象会有所帮助,所以我可以单独访问每个json对象并在其上执行不同的功能但我觉得我可能会丢失一点。

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.

推荐答案

我认为您可以将json存储在全局变量中,并根据需要循环遍历项目,从20开始,通过调用 setDivs(20) 成功加载json后。

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;
}

我还添加了更新的代码#mason-content 元素,点击页面上的#next20 元素,从json对象接下来的20个div。

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.

当然,我不知道你的 #masonry-content 元素是否为空。如果不是,那么在 #masonry-中添加类似< div id =json-data>< / div> 的内容content 元素,并通过用替换 $('#masonry-content)的两个实例来相应地更新上述代码$('#json-data')

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')

如果 data [results] [i] 不起作用,也许可以尝试 data.results [i]

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

如果您正在使用Chrome,拉起控制台(CTRL + SHIFT + J)并输入数据然后按回车。如果JSON成功加载,您应该能够探索到的树然后你可以在控制台中玩它,尝试 data [results] data.results 数据[结果] [0] 并确认它拉出第一项。

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).

更新:

这是一个有效的工作 JSON / AJ AX Ticker 示例,每4.5秒随机交换项目。它的建立是为了响应twhyler的关于stackoverflow的后续问题

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.

这篇关于在初始.ajax调用之外使用JSON数据 - 访问剩余的JSON数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆