简体   繁体   中英

How to create a JavaScript wrapper that can access a function and it's objects?

I have the following code that must be intact and cannot be modified.

        function newUser(username, email, callback) {
            var xhr = new XMLHttpRequest();
            var response;
            var success = (!!Math.round(Math.random()));

            if (!success){
                response = JSON.stringify({
                    success: success,
                    error: "Oups, something went wrong!"
                });
            } else {
                response = JSON.stringify({
                    success: success,
                    user: {
                        username: username,
                        email: email
                    }
                });   
            }

            xhr.open("POST", "/echo/json/");
            xhr.onload = function () {
                    if (xhr.status === 200) {
                        callback(JSON.parse(xhr.responseText));
                }
            }
            xhr.send("json=" + response);
        };

First I would like to call a function (newUser) on Click and then I would like to display and alert when the AJAX request within that function is successful. So far I have something similar to

            var el = document.getElementById("myButton");
            el.onclick = addUser;

               if (success){
                    alert (‘successful’);
                    }

Since I can't modify the addUser function I figured that I need to add some sort of JavaScript wrapper to access it. Maybe I'm overthinking it but I can't get it to work.

Not entirely sure I understand your question, but let me try to help. Specify a handler function:

function onSuccess(result){
   alert (‘successful’)
}

Then call newUser :

el.onclick = addUser("userName", "userEmal", onSuccess);

onSuccess will be invoked in case of a 200 response, per the source code you provided.

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