在函数中无法在jQuery $ .get中访问全局变量 [英] Can't access global variable in jQuery $.get within function

查看:413
本文介绍了在函数中无法在jQuery $ .get中访问全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我遇到的一些代码。基本上,我将空数组定义为全局变量(var playlist = []),然后尝试在jQuery $ .get调用中向其添加元素。从我在网上阅读的内容中,我应该可以做到这一点!下面的代码给出了错误:不能调用未定义的方法播放。播放列表[0]在函数中设置,在$ .get调用中提醒播放列表[0]给出预期的结果,但它不会在函数外持续存在。

  var playlist = []; 
函数playArtist(artist){
$ .get('media / songs /'+ artist,
function(data){
for(var i in data){
playlist [i] = setSong(data [i] .Resource.name,'track'+ data [i] .Media.id,i + 1);
}
$('#track text(parseInt(playlist.length));
},'json'
);
playlist [0] .play();
}

任何人都可以帮忙吗?

谢谢!

解决方案

有可能, playlist 在 $。get 返回之前 - 因为ajax调用是异步的。它在成功回调中工作,因为一旦请求完成,它就会被触发,所以它会包含你期望的数据。


Below is some code I'm having trouble with. Basically, I'm defining an empty array as a global variable (var playlist = []) and then trying to add elements to it within a jQuery $.get call. From what I've read on the internet, I should be able to do this! The following code gives the error: "Cannot call method 'play' of undefined". playlist[0] does get set within the function, alerting playlist[0] within the $.get call gives the expected result, but it doesn't persist outside the function.

var playlist = [];
function playArtist(artist){
  $.get('media/songs/' + artist,
    function(data){
      for (var i in data){
        playlist[i] = setSong(data[i].Resource.name,'track' + data[i].Media.id,i + 1);
      }
    $('#track-total').text(parseInt(playlist.length));
    },'json'
  );
  playlist[0].play();
}

Can anyone help?

Thanks!

解决方案

Chances are, playlist is getting used before $.get returns - as ajax calls are asynchronous. It works within the success callback because that gets fired once the request has completed, so it will contain the data you expect.

这篇关于在函数中无法在jQuery $ .get中访问全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆