AJAX in Spring MVC requests and returns an example of JSON

  • 2020-05-30 20:07:45
  • OfStack

1. Return as ModelAndView

Take a look at the JavaScript code first:


/**
 *  save - synchronous ( Version control library )
 */
function saveSynchronizedVcHorse(obj) {
  var ss = $("#SynchronizedSelection div");
  var cacheSelectAry = new Array()
  for(var i = 0; i < ss.length; i ++) {
    //alert(ss.eq(i).html());
    //alert(ss.eq(i).find('label').html());
    var o=ss.eq(i).find('label').find("input[type='checkbox']");
    
    var s = $(o).attr('checked');// Due to the $(obj).attr("checked", false); checked Attribute will be 
    if(s != null) {
      cacheSelectAry.push($(o).attr('value'));
    } 
  }
  if(cacheSelectAry.length == 0) {
    alert(" Please select city ");
    return;
  }
  var json = "SynchronizedBean={\"exceptionId\":\""+exceptionId+"\",\"cityIds\":["
  for(var i = 0; i < cacheSelectAry.length; i ++) {
    if(i == cacheSelectAry.length -1) {
      json = json +"\""+ cacheSelectAry[i] + "\"";
    } else {
      json = json + "\"" + cacheSelectAry[i] + "\",";
    }
  }
  json = json + "]}";
  $.ajax({
      type: "POST",
      dataType: "json",
      url: "../main/saveSynchronizedData",
      data: json,
      success: function(msg){
        alert(msg.main);
      },
      error: function () {//XMLHttpRequest, textStatus, errorThrown
        alert(" The request failed "); 
      } 
  });
}

The main thing to look at is the ajax request section.

Now look at the code for the controller in Spring:


@RequestMapping(value = "/saveSynchronizedData", method = RequestMethod.POST)
  public @ResponseBody ModelAndView saveSynchronizedData(@RequestParam("SynchronizedBean") String mSynchronizedJSON) {
    ObjectMapper objectMapper = new ObjectMapper();
    Map<String, String> map = new HashMap<String, String>();
    try {
      SynchronizedBean bean = objectMapper.readValue(mSynchronizedJSON, SynchronizedBean.class);
      if(bean != null) {
        String[] ary = bean.getCityIds();
        if(ary != null && ary.length > 0) {
          for(String s : ary) {
            VCHousePo po = new VCHousePo();
            po.setExceptionId(bean.getExceptionId());
            po.setCustomerCode(s);
            po.setCreateTime(new Date());
            po.setExceptionState(0);
            vcHService.add(po);
          }
        }
      }
      map.put("msg", "success");
    } catch (JsonParseException e) {
      e.printStackTrace();
      map.put("msg", "error");
    } catch (JsonMappingException e) {
      e.printStackTrace();
      map.put("msg", "error");
    } catch (IOException e) {
      e.printStackTrace();
      map.put("msg", "error");
    }
    return new ModelAndView(new MappingJackson2JsonView(),map);
  }

This is an ModelAndView way to return JSON. Also: MappingJackson2JsonView USES package

import org.springframework.web.servlet.view.json.MappingJackson2JsonView;


Related articles: