简体   繁体   中英

Define custom handle function for $.post ajax request

function getUsers()
{
    $.post("/admin/getusers",
    {
        username: username_input.val()
    }, showUsers(data));
}

ERROR: Uncaught ReferenceError: data is not defined at getUsers

How can i specify custom callback function for ajax request?

data should be an argument in a callback function definition, not a variable that you use as a parameter in a function invocation:

function callback(data) { /* data is available here */ }

You can pass this function definition as your callback argument:

 $.post("/admin/getusers", ...,  function callback(data) { /* data is available here */ });

And then call your showUsers inside the function body, where data is available when the function gets called after the response is received:

 $.post("/admin/getusers", ...,  function callback(data) { showUsers(data) });

Or to make it shorter, and ES6-y:

 $.post("/admin/getusers", ...,  data => showUsers(data));

It looks like showUsers is your success function, so simply pass it as:

$.post("/admin/getusers", {
  username: username_input.val()
}, showUsers);

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