开发者

Scoping inside Javascript anonymous functions

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

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;
}

Which means that inside the anonymous 'success' function I have no way of knowing what the calling obj (or id) actually are. The only way I can think of doing it is to attach id to document but that just seems a bit too crude. Is there another way of doing this?


You can use variables from the enclosing scope, a technique called "closure". 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;
}


If you are attempting to load html onto the page via ajax you may want to consider the load() function.


Functions in JavaScript become enclosed in the scope in which they are defined (this is a closure). In this case, a new anonymous success callback function is created every time ajax_submit() is called, so all the variables from the parent scope will always be accessible.

Your code should work just fine as is. If you want to have a callback function, it can be passed as an argument to ajax_submit() and called like this:

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


The variables obj, id and message are all available within the anonymous function.

This is because of a feature in Javascript called closures, which I advise you read up on.

The general gist of a closure is that a function will forever have access to the variables that were present in the scope it was defined in.

The result of this is that you can do:

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

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜