Javascript 在使用ajax发送之前填充数组

Javascript 在使用ajax发送之前填充数组,javascript,jquery,arrays,ajax,Javascript,Jquery,Arrays,Ajax,我不是JavaScript方面的专家(尤其是承诺和回调),但我基本上是想让我的JavaScript文件同步执行以下任务: 1.创建一个数组 2.将我需要的每个元素都放入数组中 3.使用post ajax调用将阵列发送到控制器。 以下是我正在使用的函数: function initialize() { var detroit = new google.maps.LatLng(42.331427, -83.0457538); map = new google.maps.Map(doc

我不是JavaScript方面的专家(尤其是承诺和回调),但我基本上是想让我的JavaScript文件同步执行以下任务: 1.创建一个数组 2.将我需要的每个元素都放入数组中 3.使用post ajax调用将阵列发送到控制器。 以下是我正在使用的函数:

function initialize() {
    var detroit = new google.maps.LatLng(42.331427, -83.0457538);
    map = new google.maps.Map(document.getElementById('map'), {
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        center: detroit,
        zoom: 15
    });
    var request = {
        location: detroit,
        radius: 500,
        types: ['restaurant']
    };
    infowindow = new google.maps.InfoWindow();
    service = new google.maps.places.PlacesService(map);
    var promise = new Promise(function (resolve, reject) {
        service.search(request, callback);
    });
    promise.then(returnList);
}

function callback(results, status) {
    if (status === google.maps.places.PlacesServiceStatus.OK) {
        for (var i = 0; i < results.length; i++) {
            restaurantCount = results.length;
            createMarker(results[i]);
        }
    }

    function createMarker(place) {
        var placeLoc = place.geometry.location;
        var marker = new google.maps.Marker({
            map: map,
            position: place.geometry.location
        });
        var request = {
            reference: place.reference
        };
        service.getDetails(request, function (details, status) {
            foodPlace = {
                PlaceID: details.place_id,
                Name: details.name,
                PriceLevel: details.price_level,
                WebSite: details.website,
                Rating: details.rating,
                AddressNumber: details.formatted_address,
                PhoneNumber: details.formatted_phone_number,
            };
            listOfRestaurants.push(foodPlace);
            //ajaxHelper('/api/Restaurants/', 'POST', foodPlace);
            google.maps.event.addListener(marker, 'click', function () {
                infowindow.setContent(details.name + "<br />" + details.formatted_address + "<br />" + details.website + "<br />" + details.rating + "<br />" + details.formatted_phone_number + "<br />" + details.price_level);
                infowindow.open(map, marker);
            });
        });
    }

    function returnList() {
        if (restaurantCount == listOfRestaurants.length) {
            $.ajax({
                url: '/Home/Index',
                data: listOfRestaurants,
                type: 'POST',
                traditional: true,
                success: alert("yay")
            }).fail(alert("oops"));
        }
    }
在窗口完成加载后开始初始化功能

我遇到的问题是,数据总是在列表有任何数据之前通过ajax调用发送。
如果有任何帮助或建议,我将不胜感激。

请在您的
返回列表
回调中添加一个
async:false
,因为它只允许在该请求结束时发生其他请求/操作

function returnList() {
    if (restaurantCount == listOfRestaurants.length) {
        $.ajax({
            url: '/Home/Index',
            async: false,
            data: listOfRestaurants,
            type: 'POST',
            traditional: true,
            success: alert("yay")
        }).fail(alert("oops"));
    }
}

注意:据我所知,您应该在
promise
对象上使用
done()
而不是
then()
,因为您希望
returnList
函数仅在延迟对象已解决时提取/发送数据,如果延迟对象已解决,则不调用该函数,已拒绝,或仍在进行()。

您正在进行初始异步调用以获取位置的位置,当该调用返回时,您将进行多个异步调用以获取每个位置的详细信息。您需要等待所有这些调用返回,然后才能发布数据

您可以通过创建一个JQuery延迟对象数组来实现这一点,每个调用一个对象来获取位置的详细信息。然后,您可以使用
$.when()
函数在解析所有延迟对象后执行代码

jQuery(function($) {
    var detroit = new google.maps.LatLng(42.331427, -83.0457538);

    var map = new google.maps.Map($('#map')[0], {
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        center: detroit,
        zoom: 15
    });

    var infowindow = new google.maps.InfoWindow();
    var service = new google.maps.places.PlacesService(map);

    var request = {
        location: detroit,
        radius: 500,
        types: ['restaurant']
    };

    // Make the request to get the places for the location.
    service.search(request, function(places, status) {
        if (status === google.maps.places.PlacesServiceStatus.OK) {
            // For each place returned for the location, make a request to get
            // the details. An array of JQuery Deferred objects is created for
            // the requests.
            var deferreds = $.map(places, function(place) {
                return getDeferredFoodPlace(place);
            });

            // The "done" callback will be executed when all the Deferred
            // objects are resolved, that is, when all the requests for
            // details have returned.
            $.when.apply($, deferreds).done(function() {
                // Use "$.makeArray()" to convert the arguments to the
                // "done" callback to an array, and then use "$.map()"
                // to weed out the nulls.
                var foodPlaces = $.map($.makeArray(arguments), function(foodPlace) {
                    return foodPlace;
                });

                // Create the markers for the food places that were
                // successfully returned.
                $.each(foodPlaces, function(i, foodPlace) {
                     createMarker(foodPlace);
                });

                // This is where the food places that were successfully
                // returned can be posted to the server.
            });
        }
    });

    // This function creates a JQuery Deferred object that is resolved
    // when the service.getDetails() call returns. that is, when its
    // callback function is called.
    function getDeferredFoodPlace(place) {
        return $.Deferred(function(deferred) {
            service.getDetails({
                reference: place.reference
            }, function(details, status) {
                if (status === google.maps.places.PlacesServiceStatus.OK) {
                    deferred.resolve({
                        Location: place.geometry.location,
                        PlaceID: details.place_id,
                        Name: details.name,
                        PriceLevel: details.price_level,
                        WebSite: details.website,
                        Rating: details.rating,
                        AddressNumber: details.formatted_address,
                        PhoneNumber: details.formatted_phone_number
                    });
                } else {
                    // If the call to get the details fails, this code
                    // will still resolve the Deferred object, but with
                    // a null value. Notice that null values are ignored
                    // in the "done" callback for the "$.when()" call.
                    // This means the places for which the details could
                    // not be obtained will simply be ignored with no
                    // error message.
                    // Alternatively, we could call ".reject()" instead
                    // of ".resolve()". That would cause the "fail"
                    // callback for the "$.when()" call to be executed.
                    // An error message could then be displayed, but
                    // it would mean everything fails if one fails.
                    deferred.resolve(null);
                }
            });
        });
    }

    // This functions creates a marker on the map for the given food place.
    function createMarker(foodPlace) {
        var marker = new google.maps.Marker({
            map: map,
            position: foodPlace.Location
        });
        google.maps.event.addListener(marker, 'click', function() {
            infowindow.setContent(foodPlace.Name + "<br />"
                + foodPlace.AddressNumber + "<br />"
                + foodPlace.WebSite + "<br />"
                + foodPlace.Rating + "<br />"
                + foodPlace.PhoneNumber + "<br />"
                + foodPlace.PriceLevel);
            infowindow.open(map, marker);
        });
    }
});
jQuery(函数($){
var detroit=new google.maps.LatLng(42.331427,-83.0457538);
var map=new google.maps.map($('#map')[0]{
mapTypeId:google.maps.mapTypeId.ROADMAP,
中心:底特律,
缩放:15
});
var infowindow=new google.maps.infowindow();
var service=newgoogle.maps.places.PlacesService(地图);
var请求={
地点:底特律,
半径:500,
类型:[“餐厅”]
};
//请求获取该位置的位置。
服务搜索(请求、功能(位置、状态){
if(status==google.maps.places.PlacesServiceStatus.OK){
//对于为该位置返回的每个位置,请求获取
//详细信息。为创建JQuery延迟对象数组
//请求。
变量延迟=$.map(位置,函数(位置){
返回被推迟的食物地点(地点);
});
//当所有的请求都被延迟时,“done”回调将被执行
//对象被解析,也就是说,当
//详情已返回。
$.when.apply($,延迟).done(函数(){
//使用“$.makeArray()”将参数转换为
//“完成”回调到数组,然后使用“$.map()”
//清除空值。
var foodPlaces=$.map($.makeArray(参数),函数(foodPlace){
返回食物位置;
});
//为被选中的食物位置创建标记
//成功返回。
$。每个(foodPlace,函数(i,foodPlace){
createMarker(foodPlace);
});
//这就是成功举办美食节的地方
//返回的数据可以发布到服务器。
});
}
});
//此函数创建一个已解析的JQuery延迟对象
//当service.getDetails()调用返回时
//调用回调函数。
功能getDeferredFoodPlace(位置){
return$.Deferred(函数(Deferred)){
service.getDetails({
参考:place.reference
},功能(详细信息、状态){
if(status==google.maps.places.PlacesServiceStatus.OK){
推迟,解决({
位置:place.geometry.Location,
PlaceID:details.place\u id,
Name:details.Name,
PriceLevel:details.price\u level,
网址:details.WebSite,
评级:详情。评级,
AddressNumber:details.formatted\u地址,
电话号码:details.formatted\u电话号码
});
}否则{
//如果获取详细信息的调用失败,则此代码
//仍将解析延迟对象,但使用
//空值。请注意,将忽略空值
//在“$.when()”调用的“done”回调中。
//这意味着详细信息可以显示的位置
//不被获得将被忽略,没有
//错误消息。
//或者,我们可以调用“.reject()”
//“.resolve()”的。这将导致“失败”
//要执行的“$.when()”调用的回调。
//然后可能会显示一条错误消息,但是
//如果一个人失败了,那就意味着一切都失败了。
延迟。解析(空);
}
});
});
}
//此函数用于在地图上为给定的食物位置创建标记。
函数createMarker(foodPlace){
var marker=new google.maps.marker({
地图:地图,
位置:foodPlace.位置
});
google.maps.event.addListener(标记'click',函数(){
infowindow.setContent(foodPlace.Name+“
” +foodPlace.AddressNumber+“
” +foodPlace.WebSite+“
” +foodPlace.Rating+“
function returnList() {
    if (restaurantCount == listOfRestaurants.length) {
        $.ajax({
            url: '/Home/Index',
            async: false,
            data: listOfRestaurants,
            type: 'POST',
            traditional: true,
            success: alert("yay")
        }).fail(alert("oops"));
    }
}
jQuery(function($) {
    var detroit = new google.maps.LatLng(42.331427, -83.0457538);

    var map = new google.maps.Map($('#map')[0], {
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        center: detroit,
        zoom: 15
    });

    var infowindow = new google.maps.InfoWindow();
    var service = new google.maps.places.PlacesService(map);

    var request = {
        location: detroit,
        radius: 500,
        types: ['restaurant']
    };

    // Make the request to get the places for the location.
    service.search(request, function(places, status) {
        if (status === google.maps.places.PlacesServiceStatus.OK) {
            // For each place returned for the location, make a request to get
            // the details. An array of JQuery Deferred objects is created for
            // the requests.
            var deferreds = $.map(places, function(place) {
                return getDeferredFoodPlace(place);
            });

            // The "done" callback will be executed when all the Deferred
            // objects are resolved, that is, when all the requests for
            // details have returned.
            $.when.apply($, deferreds).done(function() {
                // Use "$.makeArray()" to convert the arguments to the
                // "done" callback to an array, and then use "$.map()"
                // to weed out the nulls.
                var foodPlaces = $.map($.makeArray(arguments), function(foodPlace) {
                    return foodPlace;
                });

                // Create the markers for the food places that were
                // successfully returned.
                $.each(foodPlaces, function(i, foodPlace) {
                     createMarker(foodPlace);
                });

                // This is where the food places that were successfully
                // returned can be posted to the server.
            });
        }
    });

    // This function creates a JQuery Deferred object that is resolved
    // when the service.getDetails() call returns. that is, when its
    // callback function is called.
    function getDeferredFoodPlace(place) {
        return $.Deferred(function(deferred) {
            service.getDetails({
                reference: place.reference
            }, function(details, status) {
                if (status === google.maps.places.PlacesServiceStatus.OK) {
                    deferred.resolve({
                        Location: place.geometry.location,
                        PlaceID: details.place_id,
                        Name: details.name,
                        PriceLevel: details.price_level,
                        WebSite: details.website,
                        Rating: details.rating,
                        AddressNumber: details.formatted_address,
                        PhoneNumber: details.formatted_phone_number
                    });
                } else {
                    // If the call to get the details fails, this code
                    // will still resolve the Deferred object, but with
                    // a null value. Notice that null values are ignored
                    // in the "done" callback for the "$.when()" call.
                    // This means the places for which the details could
                    // not be obtained will simply be ignored with no
                    // error message.
                    // Alternatively, we could call ".reject()" instead
                    // of ".resolve()". That would cause the "fail"
                    // callback for the "$.when()" call to be executed.
                    // An error message could then be displayed, but
                    // it would mean everything fails if one fails.
                    deferred.resolve(null);
                }
            });
        });
    }

    // This functions creates a marker on the map for the given food place.
    function createMarker(foodPlace) {
        var marker = new google.maps.Marker({
            map: map,
            position: foodPlace.Location
        });
        google.maps.event.addListener(marker, 'click', function() {
            infowindow.setContent(foodPlace.Name + "<br />"
                + foodPlace.AddressNumber + "<br />"
                + foodPlace.WebSite + "<br />"
                + foodPlace.Rating + "<br />"
                + foodPlace.PhoneNumber + "<br />"
                + foodPlace.PriceLevel);
            infowindow.open(map, marker);
        });
    }
});