情况,页面需要保存数据,然后使用ajax请求后台,根据返回码提示保存成功还是失败。
先上代码
jsp页面代码:
<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<jsp:include page="/WEB-INF/jsp/index/head.jsp"/>
<div class="acs-body">
<jsp:include page="/WEB-INF/jsp/common/left.jsp"/>
<div class="acs-body-right">
<link rel="stylesheet" href="/css/setting/project-info.css">
<div class="list">
<div class="acs-title">项目信息
<button class="glyphicon acs-return-btn" onclick="window.history.back()">返回</button>
</div>
<div class="acs-content-list">
<div class="acs-table-box ">
<form name="list-form" class="layui-form projectInfo" type="POST" data-target="acs-body-right" action="${pageContext.request.contextPath}/projectInfo/save" >
<p><span style="font-family:'微软雅黑';">说明:此信息将在咻咻开门APP上对认证用户展示。</span></p>
<br><br>
<div class="form-item">
<label>联系人</label>
<input type="text" id="contactName" name="contactName" value="${projectInfo.contactName}">
</div>
<div class="form-item">
<label>联系电话</label>
<input type="text" id="contactPhone" name="contactPhone"
value="${projectInfo.contactPhone}">
</div>
<div class="form-item">
<label> </label>
<button class="acs-confirm-btn" onclick="saveProjectInfo();">保存</button>
</div>
<input type="hidden" id="projectId" name="projectId" value="${projectInfo.projectId}">
</form>
</div>
</div>
</div>
</div>
<script type="text/javascript" src="/js/setting/projectInfo.js"></script>
</div>
<jsp:include page="/WEB-INF/jsp/index/foot.jsp"/>
js代码:
function saveProjectInfo(){
var contactName = $("#contactName").val();
var contactPhone = $("#contactPhone").val();
var projectId = $("#projectId").val();
var data = {
contactName: contactName,
contactPhone: contactPhone,
projectId: projectId
};
$.post("/projectInfo/save", data, function (result) {
if (result.code === 0) {
acs.info("保存成功"); // 提示成功
$.pjax({
url: '/projectInfo/index',
data:{},
container: '.acs-body-right',//刷新的容器
fragment: '.acs-body-right',//获取的容器
type: 'GET'
});
} else {
acs.warn(result.msg); // 提示失败
}
});
}
java Controller 代码
@RequestMapping("save")
@ResponseBody
public Result saveProjectInfo(ProjectInfoApi projectInfoApi) {
int num =projectInfoService.saveProjectInfo(projectInfoApi);
if(num==0){
ResultUtil.getFailResult(1,"保存失败");
}
return ResultUtil.getSuccessResult();
}
}
就是这么一个代码情况,结果就是不能正确提示,后来根据页面F12提示才找到原因,粗心的我在页面中更没有引用js进去。并且页面的form表单action也会影响到button的onclick方法。引入js将form的action删掉就可以了。
没找到原因之前,还以为我使用ajax的姿势不对。写代码还是要细心。立贴自省~好记性不如烂笔头。