从Ajax函数返回值

时间:2015-04-03 19:56:21

标签: javascript ajax json

我正在尝试创建一个文本块,当文本从Json字符串更改时将自动更新。

基本上我开始于:

function streamSong(index) {
        if (!isUndefined(myPlaylist[index].title))
            return myPlaylist[index].title;
        else return '';
    }

然后修改它看起来像这样:

function streamSong(index) {
        var currentSongName = 'here';
        if (!isUndefined(myPlaylist[index].title)) {
                        var intervalFunc = function(){
                            var jsonData = null;
                            $.ajax({
                            url: 'http://www.thesite.com/pullJson.php?stream=rapstation',
                            dataType: "json",
                            data: { get_param: 'employees' },
                            success: function (data) { 
                              currentSongName = 'now here';
                            },
                            error: function (data) { 
                              currentSongName = 'not working';
                            }
                          });
                        };
                        setInterval (intervalFunc, 60000);
                        setTimeout (intervalFunc, 1);
                        return currentSongName;
        }
        else return 'no title';
    }

第一个功能点亮了并返回了我的Stream Title。 第二个函数触发,但我永远无法修改currentSongName的值。

我仍然对Javascript和ajax有点新意,所以请原谅我的无知,但我显然希望最终将currentSongName的值设置为我检索的Json值,但是现在我只想让它能够更改值在计时器上。

我是不是错了?

1 个答案:

答案 0 :(得分:1)

变量修改得很好,但为时已晚。 AJAX调用是异步的,因此该变量用于在将值赋给它之前返回值。

您将使用回调来处理结果。使用原始代码,它看起来像这样:

function streamSong(index, callback) {
    if (!isUndefined(myPlaylist[index].title)) {
        callback(myPlaylist[index].title);
    } else {
        callback('');
    }
}

用法:

streamSong(42, function(title) {
  // do what you want with the title
});

对于AJAX调用,回调将像这样使用:

function streamSong(index, callback) {
    var currentSongName = 'here';
    if (!isUndefined(myPlaylist[index].title)) {
        var intervalFunc = function(){
            var jsonData = null;
            $.ajax({
                url: 'http://www.thesite.com/pullJson.php?stream=rapstation',
                dataType: "json",
                data: { get_param: 'employees' },
                success: function (data) { 
                    callback('now here');
                },
                error: function (data) { 
                    callback('not working');
                }
            });
        };
        setInterval (intervalFunc, 60000);
        setTimeout (intervalFunc, 1);
    } else {
        callback('no title');
    }
}