Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/375.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 变量拒绝在jQuery.get回调函数中取值_Javascript_Jquery_Variables_Asynchronous - Fatal编程技术网

Javascript 变量拒绝在jQuery.get回调函数中取值

Javascript 变量拒绝在jQuery.get回调函数中取值,javascript,jquery,variables,asynchronous,Javascript,Jquery,Variables,Asynchronous,我检测一个值是否存储在localStorage中(如果localStorage存在),如果它不在数据库中(或者用户没有带有localStorage的浏览器),那么我运行一个AJAX GET请求 if (Modernizr.localstorage) { // there is storage artist = localStorage.getItem('artist'); if (!artist) { // but no cache art

我检测一个值是否存储在localStorage中(如果localStorage存在),如果它不在数据库中(或者用户没有带有localStorage的浏览器),那么我运行一个AJAX GET请求

if (Modernizr.localstorage) {
    // there is storage
    artist = localStorage.getItem('artist');
    if (!artist) {
        // but no cache
        artist = fetchArtist();
        localStorage.setItem('artist', artist)
    }
} else {
    // there's no storage
    artist = fetchArtist();
}
function fetchArtist() {
    var fetchedArtist;
    var recentTracks;
    $.get('script.php', [], function(data) {
        recentTracks = data.recenttracks;
        fetchedArtist = ((recentTracks !== undefined) ? recentTracks.track.artist['#text'] : 'Last.fm connection failed.');
    }, 'json');
    return fetchedArtist;
}

php只获取一个JSON字符串,jQuery将其转换为数据对象。我可以看出问题所在:因为$.get是异步的,所以在函数可以分配我所追求的值之前,会返回fetchedArtist变量,但是我想不出一个整洁的方法来实现这一点(可能是全局变量,但我真的不希望)。我可以在$.get中对fetchedArtist变量和我要查找的值进行console.log,但是fetchArtist函数总是返回未定义的值。

您必须通过从
fetchArtister()中删除返回语句来异步化工作流
函数,因为由于
$.get
请求的异步行为,它无法执行您需要的操作

试着这样做:


if (Modernizr.localstorage) {
    // there is storage
    var artist = localStorage.getItem('artist');
    if (!artist) {
        // but no cache
        fetchArtist();
    } else {
        doWhatYouNeedWithArtist( artist );
    }
} else {
    // there's no storage
    fetchArtist();
}

function fetchArtist() {
    var fetchedArtist;
    var recentTracks;
    $.get('script.php', [], function(data) {
        recentTracks = data.recenttracks;
        fetchedArtist = ((recentTracks !== undefined) ? recentTracks.track.artist['#text'] : 'Last.fm connection failed.');
        if ( Modernizr.localstorage ) {
                Modernizr.localstorage.setItem('artist', fetchedArtist);
        }
        // then do your stuff
        doWhatYouNeedWithArtist( fetchedArtist );
    }, 'json');
}

function doWhatYouNeedWithArtist( artists ) {
    // do stuff
}
希望这有帮助!再见