简体   繁体   中英

How to access variable in JS closure function

my code:

function addMarkerDraggable(group_id) {
    // get current view center location
    var current_view = map.getCenter();
    var current_lat = current_view.lat();
    var current_lng = current_view.lng();
    var mp_id;

    // ajax add marker to db.
    $.ajax({
        url: base_url+'myplaces/control/addplace/'+group_id,
        type: 'POST',
        data: csrf_name+'='+nocsrf_val+'&mp_latitude='+current_lat+'&mp_longitude='+current_lng,
        dataType: 'json',
        success: function(data) {
            if (data.result === true) {
                var mp_id = data.mp_id;
            }
        }
    });

    console.log(mp_id); // #pos.1

    if (mp_id != 'undefined' && mp_id != '') {
        var marker_icon = 'red.png';
        var marker = new google.maps.Marker({
            draggable: true,// ให้ลาก marker ได้ก็กำหนดเป็น true
            position: current_view,
            icon: iconBase + marker_icon,
            map: map,
            title: ''
        });

        google.maps.event.addListener(marker, 'dragend', function() {
            update_position = marker.getPosition();
            update_lat = update_position.lat();
            update_lng = update_position.lng();
            console.log(mp_id); // #pos.2
            ajaxUpdateMarkerDraggedPosition(mp_id, update_lat, update_lng);
        });
    }
}// addMarkerDraggable

It seems that i cannot set var mp_id from .ajax({}); and cannot get value from mp_id variable from #pos.1 and #pos.2.

How to set mp_id from inside jquery ajax and access it from google map closure function ?

The reason this isn't working is because in your code reading like this:

        if (data.result === true) {
            var mp_id = data.mp_id;
        }

... you are declaring a new variable called mp_id, instead of changing the value of the variable in the closure. As a result, when the 'success' callback ends, the local variable mp_id falls out of scope and you are left with no changes to the mp_id in the closure.

Change the success callback to the following:

         if (data.result === true) {
            this.mp_id = data.mp_id;
         }

You will need to research what 'this' will be bound to in your situation to insure it is the closure function addMarkerDraggable.

  if (data.result === true) { var mp_id = data.mp_id; } 

This means you are creating another variable. Just remove the "var" indicator.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM