当前位置: 移动技术网 > IT编程>开发语言>Java > Spring MVC 中 AJAX请求并返回JSON的示例

Spring MVC 中 AJAX请求并返回JSON的示例

2019年07月22日  | 移动技术网IT编程  | 我要评论

一、以modelandview的方式返回

先看下javascript代码:

/**
 * 保存-同步(版本控制库)
 */
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');//由于$(obj).attr("checked", false); checked属性会被
    if(s != null) {
      cacheselectary.push($(o).attr('value'));
    } 
  }
  if(cacheselectary.length == 0) {
    alert("请选择城市");
    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("请求失败"); 
      } 
  });
}

主要是看ajax请求部分。

再看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);
  }

这里是通过modelandview的方式进行返回json的。另外:mappingjackson2jsonview使用的package是 

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

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网