简体   繁体   中英

how to get value from local variable in success function of jquery request

This is probably a basic question because I'm not particularly good at javascript and don't understand closures etc. So I'm having trouble getting variable values to pass into the call backs. In this code, how can I get the value of id to pass to the success function handler so it's available when the function returns back?

 $(document).on("click","#media-edit-form .fancybox-submit", function(event){
        var form = $(this).parents('form:first');
        var token = $("meta[name='_csrf']").attr("content");
        var header = $("meta[name='_csrf_header']").attr("content");
        var postData = form.serializeArray();
        var id = postData["id"];

        event.preventDefault ? event.preventDefault() : event.returnValue = false;

        var jqxhr = $.ajax(
            {
                url: form.attr('action'),
                type: 'POST',
                data: postData,
                headers: {'X-CSRF-TOKEN': token},
            }

         )
            .success(function(xhr) {

                var refreshZoneId = '#image-block' + id;
                var refreshZone = $(refreshZoneId);
                alert('refreshing');


            })
            .fail(function() {
                alert( "error" );
            });
    });

I think the problem is not with the variable, but with the value assigned to it.

Try

var id = $('input[name="id"]').val();

The problem is serializeArray() returns an array so postData is an array not an object so postData["id"] should return undefined which might be your problem.

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