在getJSON回调函数中检索变量集

时间:2012-06-19 18:37:52

标签: javascript jquery ajax json

我被迫使用该函数之外的getJSON回调函数中的数据。看看:

$('#stars').raty({
        score: function() {
            var $value = 0;
            var $id = <?=$id?>;
            $.getJSON("getuserrating.php?id=" + $id, function(data) {
                $.each(data, function(key, val) {
                    $value = val;
                });
            });
            return $value;
        },
    });

这是我尝试但失败了,$值仍然设置为0,虽然在回调中它肯定设置为实际值。我知道它失败的原因,因为AJAX请求是异步发送的。问题是,在回调中执行所有操作的正确方法是不可能的。如您所见,我需要在raty(插件)设置中检索JSON对象。我只想使用$ .ajax()并将其设置为同步,但文档将此标记为1.8已弃用。我宁愿不介绍一个我知道将来会被弃用的解决方案。

有什么办法可以做到这一点吗?也许我只是没有看到森林的树木,在我面前有一个简单的解决方案。在此先感谢:)

2 个答案:

答案 0 :(得分:4)

如果你需要使用ajax来获得分数,那么方法就会倒退。

首先进行ajax调用,然后将值传递给ajax成功中的score

$.getJSON("getuserrating.php?id=" + $id, function(data) {
          /* pseudo code here since I don't know the plugin and it's data requirments*/
         var score= data.score;
         $('#stars').raty({
             score: score
         });      
});

编辑:您仍然可以通过这种方式将数据传递到分数函数

答案 1 :(得分:0)

也许这(取自jquery getJSON api doc http://api.jquery.com/jQuery.getJSON/)可行:

// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.getJSON("example.json", function() {
  alert("success");
})
.success(function() { alert("second success"); })
.error(function() { alert("error"); })
.complete(function() { alert("complete"); });

// perform other work here ...

// Set another completion function for the request above
jqxhr.complete(function(){ alert("second complete"); });

只需指定另一个raty属性而不是返回。