Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

417
Views
Solicitud de publicación de Ajax en Spring MVC

Actualmente estoy tratando de llamar a una solicitud ajax desde un controlador de cambio de JavaScript para llamar a un controlador Spring MVC. Creo que la forma en que actualmente estoy llamando a la URL en mi opinión es incorrecta, ya que recibo un error 404 en el navegador cuando se activa el evento y solicito la URL. ¿Alguien puede arrojar algo de luz si tengo todo configurado correctamente?

Aquí está mi código:

 @Controller public class DataTableController { @RequestMapping(value = "/table", method = RequestMethod.GET) public String home(Model model) throws JsonGenerationException, JsonMappingException, IOException { List<String> gpnList = new ArrayList<GPN>(); gpnList.add("GPN-1"); gpnList.add("GPN-2"); gpnList.add("GPN-3"); model.addAttribute("gpnList", mapper.writeValueAsString(gpnList)); return "index"; //name of my view } @RequestMapping(value = "/getsector", method = RequestMethod.POST) public @ResponseBody String getSector(@RequestParam("market")String market) throws JsonGenerationException, JsonMappingException, IOException { List<String> sectors = new ArrayList<String>(); sectors.add("Auto"); sectors.add("Industrial"); sectors.add("Analog"); ObjectMapper mapper = new ObjectMapper(); return mapper.writeValueAsString(sectors); } }

Código Jquery:

 $(document).ready(function() { document.getElementById("markets").onchange = function() { var market = $("select[id='markets'").find('option:selected').text(); var filters = { "market" : market } filters = JSON.stringify(filters); $.ajax({ url: "/getsector", type: "POST", dataType : 'json', contentType : "application/json", data: JSON.stringify(filters), success: function(response) { console.log("sucess!"); }, error: function(e){ console.log("ERROR: ", e); } }); } });

Lo principal que quiero lograr es poder llamar a mis controladores a través de llamadas ajax. Cualquier otro consejo sobre el mapeo y las convenciones de Spring Controller será apreciado.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Si solicita información, debe usar solicitudes GET , no POST .

Está mezclando @RequestParam con una carga json. Si desea recibir su filtro como un parámetro de solicitud, debe ir a la URL, no como una carga json, usando algo como:

 $(document).ready(function() { document.getElementById("markets").onchange = function() { var market = $("select[id='markets'").find('option:selected').text(); $.ajax({ url: "/getsector?market="+market, type: "GET", success: function(response) { console.log("sucess!"); }, error: function(e){ console.log("ERROR: ", e); } }); } }); @RequestMapping(value = "/getsector", method = RequestMethod.GET) public @ResponseBody String getSector(@RequestParam("market")String market) throws JsonGenerationException, JsonMappingException, IOException { .... your logic. }

Por otro lado, si realmente desea utilizar solicitudes POST con una carga json, debe utilizar @RequestBody en el controlador y vincular el objeto json a un bean con las mismas propiedades.

 @RequestMapping(value = "/getsector", method = RequestMethod.POST) public @ResponseBody String getSector(@RequestBody Market market) throws JsonGenerationException, JsonMappingException, IOException { List<String> sectors = new ArrayList<String>(); sectors.add("Auto"); sectors.add("Industrial"); sectors.add("Analog"); return sectors; } public class Market { String market; //getter and setter... }

Tenga en cuenta que su javascript también es incorrecto, está usando JSON.stringify dos veces.

Si usa @ResponseBody y Spring está bien configurado, realizará la serialización por usted cuando devuelva la respuesta, por lo que no tiene que hacerlo manualmente.

Este código no ha sido probado, es solo para que te hagas una idea.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!