如何从 JavaScript 函数获取多个返回值
我有 JavaScript 函数调用 changeMapLocation
函数,其中我想返回变量 lat
和 long1
。我在代码中遇到一些问题,无法返回这两个变量并在函数调用中发出警报。
var sample = changeMapLocation(state);
alert(sample.lat1);
alert(sample.lat2);
function changeMapLocation(state) {
var addressval=state;
var address;
var url;
var googleUrl= "http://maps.google.com/maps/api/geocode/json?";
var sensor = "&sensor=false";
if(addressval != null && addressval !="" && addressval.length!=0) {
address = "address="+encodeURIComponent(addressval);
$.ajax({
url:googleUrl+address+sensor,
type:"POST",
dataType:"json",
success:function(longlatJson) {
var jsonObj = JSON.parse(JSON.stringify(longlatJson));
var lat = jsonObj.results[0].geometry.location.lat;
var long1 = jsonObj.results[0].geometry.location.lng;
alert(lat);
alert(long1);
//var latlng = new google.maps.LatLng(lat,long1);
//alert(latlng);
},
error:function(){alert("unable to conect to google server");}
});
}
return(lat1:lat,lat2:long1);
}
I have JavaScript function call to changeMapLocation
function where in it I want to return the variables lat
and long1
. I have some problem in code to return those two variables and alert in function call.
var sample = changeMapLocation(state);
alert(sample.lat1);
alert(sample.lat2);
function changeMapLocation(state) {
var addressval=state;
var address;
var url;
var googleUrl= "http://maps.google.com/maps/api/geocode/json?";
var sensor = "&sensor=false";
if(addressval != null && addressval !="" && addressval.length!=0) {
address = "address="+encodeURIComponent(addressval);
$.ajax({
url:googleUrl+address+sensor,
type:"POST",
dataType:"json",
success:function(longlatJson) {
var jsonObj = JSON.parse(JSON.stringify(longlatJson));
var lat = jsonObj.results[0].geometry.location.lat;
var long1 = jsonObj.results[0].geometry.location.lng;
alert(lat);
alert(long1);
//var latlng = new google.maps.LatLng(lat,long1);
//alert(latlng);
},
error:function(){alert("unable to conect to google server");}
});
}
return(lat1:lat,lat2:long1);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
你那里有一个更大的问题。您正在调用异步
$.ajax()
方法,它的回调函数将在您的changeMapLocation()
函数返回后被调用,因此您的函数将无法按您的预期工作。请遵循以下示例中的注释:您应该考虑重构代码,以便处理 ajax 响应的逻辑位于
success
回调中。示例:请注意,
changeMapLocation()
不再返回任何内容。当服务器响应 Ajax 请求时,它只会自行更改地图位置。另外请注意,您的
lat
和long1
变量包含在success
内部函数的范围内,无法从外部访问功能。You have a bigger problem in there. You are calling the asynchronous
$.ajax()
method, where its callback function will be called after yourchangeMapLocation()
function returns, and therefore your function will not work as you are expecting. Follow the comments in the example below:You should consider refactoring your code in such a way that the logic to handle the ajax response is in the
success
callback. Example:Note that
changeMapLocation()
does not return anything anymore. It will simply change the map location on its own, when the server responds to the Ajax request.In addition note that your
lat
andlong1
variables were enclosed in the scope of thesuccess
inner function, and couldn't be accessed from the outer function.将它们包装在一个对象中并返回该对象:
然后,在函数调用中:
Wrap them both up in a single object and return that object:
Then, in your function call:
您只能返回单个值。该值可以是一个对象,但语法使用
{}
而不是()
。异步 JavaScript 和 XML 是异步。就调用函数而言,它是一劳永逸的,您无法从中返回值。
您的回调必须完成任务,它不能将数据返回给其他东西来完成它。
You can only return a single value. That value can be an object, but the syntax uses
{}
not()
.And Asynchronous JavaScript and XML is Asynchronous. As far as the calling function is concerned, it is fire and forget, you don't get to return a value from it.
Your callback has to complete the task, it can't give the data back to something else to complete it.
或者稍微长一点的版本,更具可读性
Or the slightly longer version that is a little more readable
要返回多个值,您需要创建一个对象。
除此之外,此代码也无法工作,因为
$.ajax()
创建了一个异步请求,该请求的触发晚于您的return 语句
。所以你需要调用你自己的回调。喜欢
然后称之为
To return multiple values, you need to create an object.
Beside that, this code would not work either since
$.ajax()
creates an asychronous request, which fires later than yourreturn statement
does.So you need to invoke your own callback. like
and then call it like
正如其他答案中所述,使用异步调用,您将不会在 Ajax 调用后立即获取值,因为 ajax 调用不会完成。所以你得到的值是未定义的。你有两个选择:
选项1:
将你对ajax返回值所做的操作移到ajax调用的成功回调函数中。请参阅 jAndy 或 Daniel Vassallo 的回答。
选项 2:(async: false)
您可以通过为 ajax() 函数。然后,此方法将阻塞,直到收到响应,完成后,您将通过 Ajax 初始化值。
使用第二个选项,您的代码将如下所示:
As noted in other answers, with asynchronous call, you will not get the values immediately after your Ajax call since ajax call would not have completed. so you are getting the values as undefined. You have two options:
Option 1:
Move the operations you do with the return values of ajax into the success callback function of ajax call. See jAndy's or Daniel Vassallo's answer.
Option 2: (async: false)
You can make the call to be synchronous by setting the option
async: false
for ajax() function. Then this method would block until the response is received and when it completes, you will have the values initialized through Ajax.with the second option, your code would look like: