从Ajax函数返回值

Return values from an Ajax function

本文关键字:返回值 函数 Ajax      更新时间:2023-09-26

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