从回调函数获取变量 [英] Get variable from callback function

查看:80
本文介绍了从回调函数获取变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

function foreignCoordinatesArray(){

  var coordinates = [];
  $.getJSON('/critics.json?travel_id=' + $('#foreign_travel').val(), success);

  function success(ary) {
    for(var a in ary){
      var obj = ary[a];
      coordinates.push(new google.maps.LatLng(obj.latitude, obj.longitude));
    }

  }
  console.log(coordinates);
}

最后,坐标仍然是[],而不是[{...},{...},...].我想这一定是闭包的问题

At the end coordinates will still be [] and not [{...},{...},...]. I guess this must be a problem with closures

如何在坐标数组中获得所需的值?

How can I have my desired value in coordinates array?

推荐答案

闭包不是问题,而是JavaScript AJAX调用的异步特性.当AJAX调用响应到达时(调用成功函数,传播 coordinates 数组),就在您登录该数组之后(当时为空).

It's not a problem with closures but with asynchronous nature of JavaScript AJAX calls. The moment AJAX call response arrives (and your success function is called, propagating coordinates array) it is way after you logged in that array - which was empty at that time.

我猜您想以某种方式从 foreignCoordinatesArray()函数返回 coordinates .如您所见,您不能使用 return :

I guess you want to somehow return the coordinates from foreignCoordinatesArray() function. As you can see you cannot use return:

function foreignCoordinatesArray(){
  var coordinates = [];
  $.getJSON('/critics.json?travel_id=' + $('#foreign_travel').val(), success);

  function success(ary) {
    //...
  }
  return coordinates;
}

相反,您应该传递一个回调函数,该函数将接收坐标:

Instead you should pass a callback function that will receive coordinates:

function foreignCoordinatesArray(coordinatesCallback){
  var coordinates = [];
  $.getJSON('/critics.json?travel_id=' + $('#foreign_travel').val(), success);

  function success(ary) {
    //...
    coordinatesCallback(coordinates);
  }
}

顺便说一句,在将其用作URL的一部分之前,应转义 $('#foreign_travel').val().

BTW you should escape $('#foreign_travel').val() before using it as part of the URL.

这篇关于从回调函数获取变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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