js 在一个函数内如何调用另一个函数的变量

有一个函数获取当前城市的值:

function getLoaction(){
                if (navigator.geolocation)
        {
        navigator.geolocation.getCurrentPosition(showPosition, showErr);
        }
        
  function showPosition(){
    $.getJSON(url,function(data){
        var yourCurCity = data.city;
    })
}

然后在另一个函数中调用yourCurCity的值

function getWeather(){

    console.log(yourCurCity);//显示为undefine
    $.ajax(url,{
    data:{"city":yourCurCity},function(data){
        ///....
    }
    
    })


}

在getWheather函数中怎样调用showPosition 的city值

阅读 16k
3 个回答
/* jQuery < 1.5 */    
function showPosition(){
  $.getJSON(url,function(data){
    var yourCurCity = data.city;

    getWeather(yourCurCity);//需要在这儿调用,并且需要把参数传过去。
  })
}
    
function getWeather(theCity){
  console.log(theCity);
  $.ajax({
    url,
    data: {"city":theCity},
    function(data) {
      ///....
    }
  });
}
    
/* jQuery >= 1.5 */    //1.5以后,ajax相关函数返回的对象成了一个推迟对象,可以用一些额外的函数。
function showPosition() {
  $.getJSON(url)
    .done(function(data) {
      var yourCurCity = data.city;

      getWeather(yourCurCity);
  })
    .fail(function(data) {
      console.log(data);    
  });
}
        
function getWeather(theCity) {
  console.log(theCity);
  $.ajax({
    url,
    data:{"city":theCity}
  })
    .done(function(data) {
    ///...
    })
    .fail(function(data) {
      console.log(data);    
    });
}

yourCurCity声明在外部或者在getJSON成功后调用getWeather时传参。如果getWheather不是异步的话。只能采用后者,或者是进行promise回调。

异步获取的需要用回调函数 推荐 Promise 写法 避免回调金字塔

showPosition(){
    return 
    $.getJSON(url)
    .then(getWeather);
}

getWeather(data){
    console.info(data.city);
};
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题