$.getJson reuse method for rendering 2 different controls
Im doing a $.getJson call which I want to be able to reuse for different ui rendering. I want to use the GetUserRoles(userName) method for rendering 2 ui controls with 2 different calls. The first call is made to populate a dropdownlist. Now I want to make another call to the method which will draw a UL list on the same page. How do I do it using the same method.
function GetUserRoles(userName) {
var param = { userName: userName };
$.getJSON(userRoleController, param, function (data) { GetUserRolesSuccess(data, userName); });
}
function GetUserRolesSuccess(data,userName) {
$("#userdetails #roles").html("");
if (data.length != 0) {
var roles = "<table class='rolesTable' cellpadding='0' cellspacing='0' border='0'>";
for (var i = 0; i <= data.length - 1; i++) {
if (data[i] != undefined) roles += "<tr><td>" + data[i] + "</td><td><a href='#' onclick=\开发者_开发问答"RemoveUserFromRole('" + data[i] + "','" + userName + "');\">Remove</a></td></tr>";
}
roles += "</table>";
}
else {
roles = "<p class='norolesavailable'>No roles assigned to user.</p>";
}
$("#userdetails #roles").html(roles);
}
Add a parameter to GetUserRoles
and GetUserRolesSuccess
which indicates the type of control to render, so the method signatures look like GetUserRoles(userName, controlToRender)
and GetUserRolesSuccess(data, userName, controlToRender)
. Modify GetUserRoles
to look like:
function GetUserRoles(userName, controlToRender) {
var param = { userName: userName };
$.getJSON(userRoleController, param, function (data) { GetUserRolesSuccess(data, userName, controlToRender); });
}
and finally add a condition which renders a control based on the new parameter, e.g.:
function GetUserRolesSuccess(data, userName, controlToRender) {
if(controlToRender == 'ul') {
// make a ul
} else if(controlToRender == 'whatever') {
// make a whatever
}
}
Now simply call GetUserRoles
passing in your new argument, e.g.:
GetUserRoles('Jeff123', 'ul');
GetUserRoles('Jeff123', 'foo');
精彩评论