首页 > 解决方案 > 将 Javascript 变量传递给 Java 控制器(Spring-boot)

问题描述

我对此很陌生,所以在我阅读了一些关于此的解决方案但仍然没有得到它之后。

我有一个 var id = [] 并想将其传递给我的控制器以将其从数据库中删除(SQL 服务器)

我的 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 );
    } );

我的 Java 控制器

@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";
    }

}

请指导我在控制器中获取 var = id[] 非常感谢

标签: javascriptjavaspring-boot

解决方案


使用 JSON:

控制器 :

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

Ajax:- 数据: 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;
        }
    });

推荐阅读