简体   繁体   中英

Passing Javascript variable to Java Controller (Spring-boot)

I'm new to this, so after I have read some solution about this but still not get it.

I have a var id = [] and want to pass it to my controller to delete it from database (SQL server)

My JavaScript

$('#deleteButton').click( function () {
        var id = [];
        var length = table.rows('.selected').data().length;
        for(var i = 0; i < length; i++){
            id.push(table.rows('.selected').data()[i][0])
        }
        $.ajax({
             url: "", 
//idk to put what into this url
//I think to put an url to show my var but i getting 404 and
//maybe im missing something in controller
//my url to access the project is: localhost:8084
             method: 'POST',
             data: { 
                    idList: id
             },
             success: function (data) {
                 console.log(id);
             }
        });
        console.log(id);
        table.rows('.selected').remove().draw( false );
    } );

My java controller

@Controller
@ComponentScans(value = { @ComponentScan })
public class CandidateController {

    @Autowired
    CandidateServiceImp candidateService;  

//localhost:8084/manageCandidates is where i show datatable
//and var id = [] is getting from this table
    @RequestMapping(value = { "/manageCandidates"})
    public String manageCandidatesPage(Model model) {
       model.addAttribute("listCandidates",candidateService.getAllCandidates());
        return "manageCandidates";
    }

}

Please instruct me to get var = id[] in controller Thanks alot

Use JSON:

Controller :

@RequestMapping(value = "/manageCandidates", method = RequestMethod.DELETE)
    public @ResponseBody String manageCandidatesPage(HttpServletRequest request,@RequestBody String idjson) throws Exception
        System.out.println("id"+idjson);
        }

Ajax:- data: JSON.stringify(id),

$.ajax({
        url: "",
        type: "",
        async: false,
        processData: false,
        contentType: "application/json; charset=utf-8",
        data: JSON.stringify(id),
        success: function(data) {
            response = data;
        }
    });

There are three processes.

  1. Add content-type: application/json in client-side ajax.
  2. And enclose the data in JSON.stringify .
  3. If the server-side Model is properly structured, add @RequestBody before the Model.

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