我的一个JavaScript变量似乎在jQuery调用后被重置

One of my JavaScript variables seem to be getting reset after a jQuery call

本文关键字:调用 jQuery 一个 变量 JavaScript 我的      更新时间:2023-09-26

我的代码向Twitter发送搜索数据请求,并以JSON格式获得响应。在获得JSON后,它将匹配特定条件的响应计数存储在数组中。

下面是调用查询Twitter的函数的代码。

$(document).ready(function() {
...
graph = new HighCharts.chart({
    chart: {
        events: {
            load: function() {
                console.log("events.load");
                var that = this;
                var update = function() {
                if (polling) {
                    console.log("update()");
                    // The least index series will be nearest the x-axis
                    var stackNumber = 0;
                    var numTweets = updateValues();
                    console.log(numTweets + "");
                    for (var i = 0, currentSeries = that.series; i < currentSeries.length; i++) {
                        var x = (new Date()).getTime(), // current time
                        y = numTweets[i];
                        stackNumber += y;
                        currentSeries[i].addPoint([x, y], true, true);
                    }
               }
          }
          // set up the updating of the chart each second
          var series = this.series[0];
          setInterval(update, 1000);
     }
}

(我可能在代码粘贴的某个地方丢失了一些大括号,但我确信我的问题与丢失大括号无关)

这里是使用一系列jQuery调用查询Twitter的函数。updateValues()函数(在document-ready部分之外)如下所示:

    function updateValues() {
        var url = "http://search.twitter.com/search.json?callback=?&q=";
        var cls = "Penn_CIS240"
        var query = "%23" + cls;
        var voteCount = [0,0,0,0];
        // create an array of zeros
        //for (var i = 0; i < 4; i++)
        //    voteCount.push(0);
        $.getJSON(url + query, function(json){
            console.log(json);
            $.each(json.results, function(i, tweet) {
                var user = tweet.from_user_id;
                if (user % 2 == 0) {
                    voteCount[0] += 1;
                }
                else if (user % 3 == 0) {
                    voteCount[1] += 1;
                }
                else if (user % 5 == 0) {
                    voteCount[2] += 1;
                }
                else {
                    voteCount[3] += 1;
                }
                console.log("updateValues() -> getJSON -> each -> voteCount = " + voteCount);
            });
            console.log("updateValues() -> getJSON -> voteCount = " + voteCount);
        });
        console.log("updateValues() -> voteCount = " + voteCount);
        return voteCount;
    }

正在发生的是变量voteCount在jQuery调用中得到适当的增加。然而,在调用之外,它正在被重置。因此日志输出看起来像这样:

updateValues() -> getJSON -> each -> voteCount = [1,0,0,0]
updateValues() -> getJSON -> voteCount = [1,0,0,0]
updateValues() -> voteCount = [0,0,0,0]

这个问题是否与jQuery的异步调用有关,我有有趣的变量修改冲突?还是其他原因?

当你在JavaScript中使用异步回调时,它们稍后执行…异步。所以如果你有:

var x = 5;
console.log("before getJSON", 5);
$.getJSON("/some/url", function (json) {
    x = 10;
    console.log("inside callback", x);
});
console.log("after getJSON", x);

输出将是

before getJSON 5
after getJSON 5
inside callback 10

任何你想在请求返回后执行的代码都必须在回调函数中;把它放在$.getJSON调用之后是不够的。您应该将$.getJSON视为"发射"json获取进程,然后立即返回给您;只有在之后,当你的脚本执行完正常代码并且服务器已经响应时,JavaScript事件循环才会说"嘿,我得到了响应,我空闲了;是时候调用等待响应的回调了!"


因此,你的updateValues函数需要接受自己的回调,以便通知自己的调用者值已经更新;仅仅调用updateValues只会触发值更新进程,并且直到空闲时间之后才会更新值。比如:

function updateValues(onUpdated) {
    var url = "http://search.twitter.com/search.json?callback=?&q=";
    var cls = "Penn_CIS240"
    var query = "%23" + cls;
    var voteCount = [0,0,0,0];
    $.getJSON(url + query, function (json) {
        // use of json to update voteCount ellided
        onUpdated(voteCount);
    });
}

然后调用代码使用它作为

updateValues(function (voteCount) {
    // use the updated vote counts inside here.
});