1. 程式人生 > >Ajax post 請求後端,server返回Map結果集

Ajax post 請求後端,server返回Map結果集

一、應用場景

當前端發出Ajax請求,後端需要返回Map結果集

二、程式碼

1、ResultFactory.java

package com.XXXX.tv.vrs.service.util;

import java.util.HashMap;
import java.util.Map;

public class ResultFactory {
	
	public static Map<String,Object> makeOkResult(Object data){
		Map<String,Object> res = new HashMap<String,Object>();
		res.put("status", StatusCode.OK);
		res.put("msg", StatusCode.OK_MSG);
		res.put("data", data);
		return res;
	}
	
	public static Map<String,Object> makeErrorResult(){
		Map<String,Object> res = new HashMap<String,Object>();
		res.put("status", StatusCode.SERVER_ERROR);
		res.put("msg", "Error");
		res.put("data", null);
		return res;
	}

}

2、controller

@RequestMapping("/uppdateSensitiveWord.do")
@ResponseBody
public Map<String,Object> updateSensitiveWord(String sensitiveInput,String sensitiveWordBeUpdate){

		Map<String,Object> map = new HashMap<String,Object>();
		try {
			Long rs=sensitiveWordService.updateSensitiveWord(sensitiveWordBeUpdate,sensitiveInput);
			map = ResultFactory.makeOkResult(rs);
		}catch(Exception e) {
			e.printStackTrace();
			map = ResultFactory.makeErrorResult();
		}	
		return map;
	}

3、JS

function updateSensitiveWord()  {  
			var sensitiveInput=$.trim($("#sensitive").val());
			var sensitiveWordBeUpdate=$.trim($("#sensitiveWordUpdate").val());
			//alert(sensitiveWordBeUpdate+"--->"+sensitiveInput);
			$.post("uppdateSensitiveWord.do", 
				{sensitiveInput: sensitiveInput,
				sensitiveWordBeUpdate:sensitiveWordBeUpdate},
				function(rs){
					if(rs.status==200 &&rs.data!=0){
						alert("修改成功");
						window.location.reload();
					}else if(rs.status==200 &&rs.data==0){
						alert("資料庫中已存在敏感詞"+sensitiveInput+",修改失敗");
					}else{
						alert("修改失敗");
					}
			});
	    }