Jquery:如何为函数调用分配JSON值

时间:2012-03-26 15:49:26

标签: jquery json

在您说这是重复或甚至关闭之前,请阅读整篇文章。我在这里搜索过,我想要做的是与本网站上发布的内容不同。不同的是,我试图将一个JSON调用的值赋给一个函数(几个类似函数中的一个),这样我就可以添加返回的总数。

所以,如果我有这样的JSON调用:

var count;
function getMainContactCount {
    $.getJSON(url, function(data) {
       count = data;
       c= getCount(count);
       return c;
    });
}

function getCount(count) {
    return count;
}

请注意我的第二个功能是返回计数而非警报计数。这可以正常使用警报,因为警报立即发生,显然返回没有。

然后在我准备好的文档中(上面的脚本在附加的脚本文件中),我这样做:

c= getMainContactCount();
count = getCount(c);

这显然不起作用,但这是我需要做的事情的本质。我需要在我的文档中准备好从数据库中返回所有计数,然后将它们一起添加。大约有10个表,因此将所有值返回到文档中然后添加它们似乎更容易。但这可能不是正确的方法。我不想做的是提醒值,因为这不会帮助我添加值。

2 个答案:

答案 0 :(得分:1)

我认为你正在寻找这样的东西:

var count;
function getMainContactCount {
    $.getJSON(url, function(data) {
       count += data.length;
       // Whatever you you need to do with count, do it here.
       // Like this:
       alert(count) // just checking if we have the right value
                    // couldn't resist adding an alert :)
    });
}

修改

要重复使用相同的回调,请在getJSON调用之外进行定义:

 // Define a global count var
 var count;
 // Define a single callback to reuse
 var addCount = function(data) {
     count += data.length;
     alert(count); // just a test, remove the alert later
 }
 // Do several ajax calls to the json
 $.getJSON('/some_url', addCount);
 $.getJSON('/some_other_url', addCount);
 $.getJSON('/yet_another_url', addCount);

答案 1 :(得分:0)

首先,getJSON是异步的。所以getMainContactCount实际上并没有返回任何内容。

其次,count = getCount(c)相当于count = c

你想在这做什么?

如果你想获得一个值,那么以后再使用它,在加载时分割你的脚本执行

var myPageLoadingScripts = function(count){  
  //You can use count here.  
  ...
}

$(function(){
    $.getJSON(url, myPageLoadingScripts);
});