localStorage에 값이 저장되어 있는지 (localStorage가있는 경우), 데이터베이스에 없거나 (localStorage가있는 브라우저가없는 경우)) 그런 다음 AJAX GET 요청을 실행합니다.변수가 jQuery.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;
}
script.php는 jQuery가 데이터 객체로 변환하는 JSON 문자열을 가져옵니다. 나는 문제를 볼 수있다 : 왜냐하면 $ .get이 비동기 적이기 때문에, 함수가 값을 할당하기 전에 fetchedArtist 변수가 반환되었지만, 나는 이것을 수행하는 깔끔한 방법을 생각할 수 없다. 정말 오히려). console.log fetchedArtist var 안에 $ .get과 값을 넣습니다.하지만 fetchArtist 함수는 항상 정의되지 않은 값을 반환합니다.
나는 매우 친절하게 응원 할거야, 응원 해! – Alex