Detection inside Javascript Anonymous Functions

I am trying to make a function return data from an ajax call, which I can then use. The problem is that the function itself is called by many objects, for example:

function ajax_submit (obj)
{   
    var id = $(obj).attr('id');
    var message = escape ($("#"+id+" .s_post").val ());

    var submit_string = "action=post_message&message="+message;

    $.ajax({  
        type: "POST",  
        url: document.location,  
        data: submit_string,  
        success: function(html, obj) {
            alert (html);
        }  
    }); 

    return false;
}

This means that inside the anonymous “successful” function, I have no way to find out what the obj (or id) call is. The only way I can do this is to attach an identifier to the document, but that seems too rude. Is there any other way to do this?

+3
source share
4 answers

You can use variables from the enclosing area, the "close" method. So:

function ajax_submit (obj)
{   
    var id = $(obj).attr('id');
    var message = escape ($("#"+id+" .s_post").val ());

    var submit_string = "action=post_message&message="+message;

    $.ajax({  
        type: "POST",  
        url: document.location,  
        data: submit_string,  
        success: function(html) {
            alert(obj.id);  // This is the obj argument to ajax_submit().
            alert(html);
        }  
    }); 

    return false;
}
+7

html ajax, load().

+4

JavaScript , ( closure). , ajax_submit(), .

, . , ajax_submit() :


success: function(html, obj) {
    callback(html);
}
+2

obj, id message .

- Javascript, , .

The general meaning of closure is that the function will forever have access to the variables that were present in the area in which it was defined.

As a result, you can:

    success: function(html) {
        alert (id);
        alert (obj);
    } 

all day (but note that the parameter objin the success function will take precedence over the variable objin your ajax_submit function.)

0
source

Source: https://habr.com/ru/post/1743220/


All Articles