繁体   English   中英

从Ajax函数返回值

[英]Return values from an Ajax function

我正在尝试创建一个文本块,当文本从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';
    }

第一个函数正常运行并返回我的流标题。 第二个函数触发,但是我永远无法修改currentSongName的值。

我对Javascript和Ajax还是有点陌生​​,所以请原谅我的无知,但是我显然想最终将currentSongName的值设置为我检索到的Json值,但是现在我希望它能够在计时器上更改值。

我要解决所有这些错误吗?

修改该变量就可以了,但为时已晚。 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');
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM