问题描述:

I have a project using Spring and i need to create admin page using jQuery. I have a table with all users and i have a button "delete". When i click it user should be deleted from the database. Without script everything works fine but with script i can't figure out how do i make user deleted from database and how to send user login to controller. I could only remove row from table, but when i refresh the page user is still there.

Could anyone please help me how to delete user from db within script?

Table

<table id="userBase" class="data" border="1" width="100%" cellpadding="2" cellspacing="4">

<tr>

<th>Login</th>

<th>First Name</th>

<th>Last Name</th>

<th>Birthday</th>

<th>Role</th>

<th>Actions</th>

</tr>

<c:forEach items="${userList}" var="user">

<tr>

<td>${user.login}</td>

<td>${user.firstname}</td>

<td>${user.lastname}</td>

<td>${user.birthday}</td>

<td><c:if test="${user.roleid==1}">Admin</c:if>

<c:if test="${user.roleid==2}">User</c:if></td>

<td><a href="edit/${user.login}">Edit </a>

<a class="confirm" href="delete/${user.login}">Delete</a></td>

</tr>

</c:forEach>

</table>

Controller without script(it's commented now, but it works fine)

@RequestMapping("/delete/{userLogin}")

public String deleteUser(@PathVariable("userLogin") String userLogin) {

userService.remove(userService.findByLogin(userLogin));

return "redirect:/welcome";

}

Controller for script

@Controller

public class SpringController {

@Autowired

private UserService userService;

@RequestMapping(value = "/delete/{userLogin}", method = RequestMethod.POST)

@ResponseBody

public boolean updateUser(@RequestParam("userLogin") String userLogin) {

userService.remove(userService.findByLogin(userLogin));

return true;

}

}

Script

<script>

$(document).ready(function() {

$("#userBase .confirm").on("click",function() {

var conBox = confirm("Are you sure ?");

if(conBox){

var tr = $(this).closest('tr');

tr.css("background-color","#000000");

tr.fadeIn(1000).fadeOut(200, function(){

tr.remove();

});

} else {

$(this).dialog("close");

}

});

});

</script>

网友答案:

Here's what worked for me:

Table (check "Delete" link)

<table id="userBase" class="data" border="1" width="100%" cellpadding="2" cellspacing="4">
    <tr>
        <th>Login</th>
        <th>First Name</th>
        <th>Last Name</th>
        <th>Birthday</th>
        <th>Role</th>
        <th>Actions</th>
    </tr>
    <c:forEach items="${userList}" var="user">
        <tr>
            <td>${user.login}</td>
            <td>${user.firstname}</td>
            <td>${user.lastname}</td>
            <td>${user.birthday}</td>
            <td><c:if test="${user.roleid==1}">Admin</c:if>
                <c:if test="${user.roleid==2}">User</c:if></td>
            <td><a href="edit/${user.login}">Edit   </a>
                <a href="${pageContext.request.contextPath}/delete/${user.login}.json">Delete</a>
        </tr>
    </c:forEach>
</table>

Controller

@RequestMapping(value="/delete/{userLogin}", method=RequestMethod.DELETE,
        produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
@ResponseBody
public void deleteUser(@PathVariable String userLogin) {
    userService.remove(userService.findByLogin(userLogin));
}

Script

<script>
$(document).ready(function() {
    var deleteLink = $("a:contains('Delete')");
    $(deleteLink).click(function(event) {
        var conBox = confirm("Are you sure ?");
        if(conBox){
        $.ajax({
            url: $(event.target).attr("href"),
            type: "DELETE",

            beforeSend: function(xhr) {
                xhr.setRequestHeader("Accept", "application/json");
                xhr.setRequestHeader("Content-Type", "application/json");
            },

            success: function() {
                var tr = $(event.target).closest("tr");
                tr.css("background-color","#000000");
                tr.fadeIn(1000).fadeOut(200, function(){
                tr.remove();})
            }
        });
        } else {
            event.preventDefault();
        }
        event.preventDefault();
    });
});
</script>
网友答案:

On your code, you are not calling the needed url to call the handler method that will delete the user. I assume you want to do this using ajax? it would also help if you can add your markup.

What you can do is(for now since your question and your code seems pretty vague)

$(document).ready(function() {
        $("#userBase .confirm").on("click",function() {
            var conBox = confirm("Are you sure ?");
            var userLogin = "sampleOnly" //maybe somewhere in your html you have this
            var url  = "mycontroller/delete/"+userLogin //A rough guess for now
            if(conBox){

                $.post(url+userLogin,function(e){
                  var tr = $(this).closest('tr');
                  tr.css("background-color","#000000");
                   tr.fadeIn(1000).fadeOut(200, function(){
                  tr.remove();
               })

            });
            } else {
                $(this).dialog("close");
            }
        });
    });
网友答案:

If you want to send data using jQuery, I'd suggest using AJAX with REST. Here's how I'd do it:

@RequestMapping(value="delete.json", method=RequestMethod.DELETE, produces="application/json")
@ResponseBody
public Boolean deleteAjaxMultiple(@RequestBody String[] gotten)
{
    for (String login : gotten)
        userService.remove(userService.findByLogin(login));
    return true;
}

This controller handles JSON requests, in this case an array of logins. Then you'll just have to call it from JavaScript like this:

$.ajax({
    headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json'
    },
    url: '/delete.json', //or whatever url works for you
    type: 'DELETE',
    data: JSON.stringify(arr), //arr is an array of logins you want to delete
    success: function(data) {
        location.reload(true); //or do whatever you want on success
    }               
});

You need to set up Jackson for this. For more info see this and this.

相关阅读:
Top