简体   繁体   中英

jQuery callback function in callback function

I want to do something with the data I store in my var searchedUsers, the problem is that when I do the alert(searchedUsers); there is nothing in it. If I do the alert(searchedUsers); under the var user code. There is something in it.

I assume this is because the code already runs before it is fully executed. Now I guess have to add another callback function in there somewhere only it doesn't seem to work I always get errors.

function addFriend() {
    var formData = "name=" + $("#nameForm").val() + "&familyname="
            + $("#familyname").val() + "&emailaddress="
            + $("#emailaddress").val();
    var searchedUsers = [];
    $.ajax({
        type : "POST",
        url : "ControllerJavascript?action=addFriend",
        dataType : "xml",
        data : formData,
        success : function(xml) {
            $(xml).find("user").each(
                    function() {
                        var user = $(this).find("name").text().trim() + " "
                                + $(this).find("familyname").text().trim()
                                + " // " + $(this).find("email").text().trim();
                        searchedUsers.push(user);
                    });

        },
        error : function() {
            alert("An error occurred while processing XML file.");
        }
    });
    alert(searchedUsers);
    getFriends();
}

Is it possible to add another callback function so first all users are pushed to searchedUsers?

You already have this function:

success : function(xml) {
...
},

This is your callback. Just call alert after your each method:

success : function(xml) {
        $(xml).find("user").each(
                function() {
                    var user = $(this).find("name").text().trim() + " "
                            + $(this).find("familyname").text().trim()
                            + " // " + $(this).find("email").text().trim();
                    searchedUsers.push(user);
         });
         alert(searchedUsers);
    },

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