简体   繁体   中英

How to call Spring controller function from JQuery Data tables AJAX

I have a controller defined in controller.xml as

<bean name="/userController" class="UserController">

And I have UserData.jsp which renders the dynamic table as below.

    <table id="usermaintenancetable">
        <thead>
            <tr>
                <th width="10%">User Id</th>
                <th width="5%">Password</th>
                <th width="5%">Level</th>
            </tr>
        </thead>
    </table>

In datatable.js file I have to access the controller to fetch data using ajax.

$(document).ready (function() { 
   $('#usermaintenancetable').DataTable( {
        //How to call controller from here using ajax call
   });
});

I have written an ajax function like below.

"ajax" : {
        "url" : "/userController",
        "dataSrc" : "users",
        "type" : "POST"
    }

But I am getting below ajax error.

POST http://localhost:7001/userList 404 (Not Found)send @ jquery.js:10261ajax @ jquery.js:9750ra @ jquery.dataTables.js:781ga @ jquery.dataTables.js:1065(anonymous function) @ jquery.dataTables.js:2016each @ jquery.js:370each @ jquery.js:137m @ jquery.dataTables.js:1831h.fn.DataTable @ jquery.dataTables.js:3853(anonymous function) @ datatable.js:3fire @ jquery.js:3232fireWith @ jquery.js:3362ready @ jquery.js:3582completed @ jquery.js:3617

Edit: Added Controller code

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;
public class UserController extends AbstractController{
@Override
protected ModelAndView handleRequestInternal(HttpServletRequest req,
        HttpServletResponse resp) throws Exception {
     String action = ServletRequestUtils.getStringParameter(req, "action", "view");
    System.out.println("Action: " + action);
    if("list".equalsIgnoreCase(action)) {
        //added some logic to get data and set it to table
    }
    return null;
} }

Could you please help in this?

In ajax call specify

contentType: 'application/json'  and dataType: json 

and you can rewrite controller as shown below

@RequestMapping(value="userController", method=RequestMethod.GET
                produces="application/json")
public @ResponseBody String userFunciton(HttpServletRequest req,
    HttpServletResponse resp)) {

  String action = ServletRequestUtils.getStringParameter(req, "action", "view");
System.out.println("Action: " + action);
if("list".equalsIgnoreCase(action)) {
    //added some logic to get data and set it to table
}
return null;
}

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