gpt4 book ai didi

javascript - 如何从 JavaScript 函数中获取多个返回值

转载 作者:太空宇宙 更新时间:2023-11-04 14:24:21 26 4
gpt4 key购买 nike

我有对 changeMapLocation 函数的 JavaScript 函数调用,我想在其中返回变量 latlong1。我在返回这两个变量并在函数调用中发出警报的代码中遇到了一些问题。

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);
}

最佳答案

你那里有一个更大的问题。您正在调用异步 $.ajax()方法,它的回调函数将在您的 changeMapLocation() 函数返回后被调用,因此您的函数将不会像您期望的那样工作。按照以下示例中的注释进行操作:

function changeMapLocation(state) {
var lat;
var long1;
// Since the $.ajax() method is using the asynchronous XMLHttpRequest, it
// will not block execution, and will return immediately after it is called,
// without waiting for the server to respond.
$.ajax({
url: 'url-here',
type: 'POST',
success: function(longlatJson) {
// The code here will be executed only when the server returns
// a response to the ajax request. This may happen several
// milliseconds after $.ajax() is called.
var jsonObj = JSON.parse(JSON.stringify(longlatJson));
lat = jsonObj.results[0].geometry.location.lat;
long1 = jsonObj.results[0].geometry.location.lng;
// Now lat and long1 are set, but it is too late. Our
// changeMapLocation() function will have already returned.
}
});
// This part will be reached before the server responds to the asynchronous
// request above. Therefore the changeMapLocation() function returns an
// object with two properties lat1 and lat2 with an undefined value.
return {lat1: lat, lat2: long1};
}

您应该考虑重构您的代码,使处理 ajax 响应的逻辑位于 success 回调中。示例:

function changeMapLocation(state) {
$.ajax({
url: 'url-here',
type: 'POST',
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;

// Update your map location in here, or call a helper function that
// can handle it:
myGoogleMap.setCenter(new google.maps.LatLng(lat, long1));
}
});
}

请注意,changeMapLocation() 不再返回任何内容。当服务器响应 Ajax 请求时,它将自行更改 map 位置。


另外请注意,您的 latlong1 变量包含在 success 内部函数的范围内,无法访问来自外部函数。

关于javascript - 如何从 JavaScript 函数中获取多个返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3581687/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com