how to pass a value to jQuery Ajax success-handler

后端 未结 3 795
忘了有多久
忘了有多久 2021-01-13 17:23

Give the following Ajax call in jQuery:

  {
  .
  .
  .
  ,
  getSomeData: function(args, myUrl, foo) {
        $.ajax( {
        type: \"GET\",
        url:         


        
3条回答
  •  再見小時候
    2021-01-13 18:04

    @Unicron had the right answer but didn't give a good example. Check this out:

    $( 'tr.onCall' ).on( 'click', function( event ) {
        let pEvent = function() { return event; } // like a fly in amber...
        $.ajax( {
            ...
            success: function( data ) {
                let x = pEvent();   // x now equals the event object of the on("click")
            }
        });
    });
    

    By declaring the pEvent function inside the anonymous function that fires on("click"), the event object is "frozen" (encapsulated) in its original context. Even when you call it in the different context of the ajax success function, it retains its original context.

    More specific example: I'm going to open a modal dialog (styled Div) on click, but when the dialog is closed I want to return the focus to the element that was clicked to open it in the first place...

    $( 'tr.onCall' ).on( 'click', function( event ) {
        let rTarget = function() { return event.currentTarget; }
        $.ajax( {
            url: 'ajax_data.php',
            ...other settings...
            success: function( data ) {
                modal_dialog(
                    data,
                    {
                        returnTarget: rTarget(),
                        ...other settings...
                    }
                );
            }
        });
    });
    

    On success, it calls a custom function modal_dialog() (defined elsewhere), passing in an object containing various settings. The returnTarget setting contains the HTML ID attribute of the element that was clicked; so when I close the dialog I can run $(options.returnTarget).focus(); to return focus to that element.

提交回复
热议问题