如何将$ .getJSON对象存储在全局变量中并在以后导航 [英] How to store $.getJSON object in global variable and navigate through it later

查看:78
本文介绍了如何将$ .getJSON对象存储在全局变量中并在以后导航的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试JQuery,并尝试创建一个函数来从JSON返回的API获取动态数据并将其存储在全局变量中(我不知道这是否是正确/最佳的方法).

到目前为止,我是

function getdata(url){
    var data = $.ajax({
        type: 'GET',
        url: url
    });
    return data;
};

到目前为止,一切正常,但是这会返回带有"responseJSON"键的对象,我似乎找不到找到导航至此键然后在其中的数组中进行$ .each循环的方法. /p>

所以问题是:

  1. 这是正确/正确的方法吗?(否则请解释您的答案)
  2. 如何在"responseJSON"键中浏览包含数组的多维对象.

解决方案

另一种方法是将回调传递给您的函数,以便您可以在函数内设置响应处理程序,并在调用getData方法时减少代码

function getdata(url, callback){
    var data = $.ajax({
                type: 'GET',
                url: url
            }).done(callback).error(function(){
               alert('Oppps...something went wrong')
            });
    return data;
};


getData('urlstring', function(data){
   /* doSomething with data */
})

I'm experimenting with JQuery and trying to create a function to get dynamic data from a JSON returned API and store it in a global variable (I don't know if this is the right/best way to do this).

What I have so far is

function getdata(url){
    var data = $.ajax({
        type: 'GET',
        url: url
    });
    return data;
};

So far everything works fine, but this returns an object with a "responseJSON" key and I can't seem to find a way to navigate to this key and then do a $.each loop through the arrays in it.

So the questions are:

  1. Is this the right / way ( if not please explain your answer)
  2. How do you navigate through a multidimensional object containing arrays in the "responseJSON" key.

解决方案

Another approach is to pass a callback to your function so you can set the response handler within the function and less code when you call your getData method

function getdata(url, callback){
    var data = $.ajax({
                type: 'GET',
                url: url
            }).done(callback).error(function(){
               alert('Oppps...something went wrong')
            });
    return data;
};


getData('urlstring', function(data){
   /* doSomething with data */
})

这篇关于如何将$ .getJSON对象存储在全局变量中并在以后导航的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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