SpringMVC的@ResponseBody可以用来返回类似json格式的数据,此时,需要定义一个额外的dto,其实也就是一个类似于model层的封装,它内部维护的是所有关于json要返回的数据的属性,其他无用的就不用写。
(1)web层,@ResponseBody AjaxObj返回的是dto相对应的json数据
@RequestMapping("/channels/updateSort")
public @ResponseBody AjaxObj updateSort(@Param Integer[] ids) {
try {
channelService.updateSort(ids);
} catch (Exception e) {
return new AjaxObj(0,e.getMessage());
}
return new AjaxObj(1);
}
(2)dto层
/**
* 专门用来返回Ajax处理之后结果json数据的对象
* @author Administrator
*
*/
public class AjaxObj {
/**
* 0表示失败
* 1表示成功
*/
private int result;
/**
* 提示信息
*/
private String msg;
/**
* 附加对象,用来存储一些特定的返回信息
*/
private Object obj;
public int getResult() {
return result;
}
public void setResult(int result) {
this.result = result;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Object getObj() {
return obj;
}
public void setObj(Object obj) {
this.obj = obj;
}
public AjaxObj() {
}
public AjaxObj(int result, String msg, Object obj) {
super();
this.result = result;
this.msg = msg;
this.obj = obj;
}
public AjaxObj(int result, String msg) {
super();
this.result = result;
this.msg = msg;
}
public AjaxObj(int result) {
super();
this.result = result;
}
}
(3)前端
(function($){
<span style="white-space:pre"> </span>$.ajaxCheck = function(data) {
<span style="white-space:pre"> </span>if(data.result) return true;
<span style="white-space:pre"> </span>else {
<span style="white-space:pre"> </span>alert(data.msg);
<span style="white-space:pre"> </span>return false;
<span style="white-space:pre"> </span>}
<span style="white-space:pre"> </span>}
<pre name="code" class="html">$.fn.mysorttable = function(opts) {
<span> </span>function saveOrders() {
if(_isSort) {
var idArg = sortEle.sortable("serialize",{key:"ids"});
$.post("updateSort?"+idArg,function(data){
if($.ajaxCheck(data)) {
$(_that).find("tr").each(function(){
$(this).children().last().remove();
});
sortEle.sortable("disable");
_isSort = false;
}
/* if(data.result) {
$(_that).find("tr").each(function(){
$(this).children().last().remove();
});
sortEle.sortable("disable");
_isSort = false;
} else {
alert(data.msg);
}*/
});
} else {
alert("还不是排序状态");
}
}
}
})(jQuery)