`

ajax局部刷新

阅读更多
jsp页面利用jQuery.post(url,data,success(data, textStatus, jqXHR),dataType)
参数 描述
url 必需。规定把请求发送到哪个 URL。
data 可选。映射或字符串值。规定连同请求发送到服务器的数据。
success(data, textStatus, jqXHR) 可选。请求成功时执行的回调函数。
dataType 可选。规定预期的服务器响应的数据类型。 默认执行智能判断(xml、json、script 或 html)。

该函数是简写的 Ajax 函数,等价于:
$.ajax({
  type: 'POST',
  url: url,
  data: data,
  success: success,
  dataType: dataType
});

jsp:
function sendReply() {
		var url = document.forms[0].action + "?m=insertRep";
		var userId = jQuery('#userId').val();
		var msgId = jQuery('#msgId').val();
		var info = jQuery('#info').val();
		if (isEmpty(info)) {
			parent.window.jAlert("回复内容不能为空!");
/****如果这个页面是内嵌框架,那么需要加上parent需找到父窗口,在父窗口中弹出框框。********/
		} else {
			var params = {
				userId : userId,
				msgId : msgId,
				info : info
			};
			jQuery.post(url, params, sendReplyCallback, 'json');
		}
	}
function sendReplyCallback(data, status) {
		if (status == "success") { 
			if (data == "0") {
				parent.window.jAlert("操作成功!", "操作", function(flag) {
					if (flag) { 
						 parent.window.location.href = "userIndex.html";//定向,刷新页面
					}
				});
			} else {
				parent.window.location.href = "userIndex.html";
			} 
		} else if (status == "error") {
			parent.window.jAlert("操作异常!");
		} else {
			parent.window.jAlert(status);
		}
	}

后台Action处理:


String msgId = iframeUserDynamicReplyForm.getMsgId();
String info = iframeUserDynamicReplyForm.getInfo();
msgId = msgId == null ? "" : msgId.trim();
info = info == null ? "" : info.trim(); 
int co = UserMessageService.sendReply(sqlSession,loginUserId, new BigDecimal(msgId), info); 
Gson gson = new Gson();//需要导入gson-2.0.jar包
response.setContentType("text/json; charset=utf-8");
response.setHeader("Cache-Control", "no-cache");
response.getWriter().write(gson.toJson(co));
return null; 

补充一下,如果获取的json数据是对象,那么就用下面的格式,如data为User对象

$.post("test.php", { "func": "getNameAndTime" },
   function(data){
     alert(data.name); // John
     console.log(data.time); //  2pm
   }, "json");

如果获取的json数据是集合对象,那么就用下面的格式,如data为List<User>对象
JSONObject data = new JSONObject();
				data.put("resultList", users);
				response.getWriter().write(data.toString());
				return null;

$.post("test.php", { "func": "getNameAndTime" },
   function(data){
     alert(data.resultList[0].name); // John
     console.log(data.resultList[0].time); //  2pm
    $.each(data,function(i){
        alert(data.resultList[i].name);
   });
   }, "json");








分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics