ajaxtony 2020-02-03
1.前台的form表单建立,注意action、enctype的内容,
2.通过添加一个隐藏的iframe标签使form的target指向iframe来达到不跳转页面的效果,同时需要在js里获取iframe里的内容(即后台利用GSON传回来的返回值)。
代码部分:
<form id="form1" action="../PublishPostingsServlet" enctype="multipart/form-data" method="POST" target="iframe_userInterface">
<!-- 正文区域--多行文本框 -->
<textarea name="ptext" id="ptext" cols="30" rows="10"></textarea>
<!-- 图片和标签选择区域 -->
<ul id="ptext_ul">
<li>
<a id="photo" href="javaScript:;" onclick="showPic();">
<em class="iconfont"></em>图片
</a>
</li>
<li id="lable">
<a href="javaScript:;" onclick="showLable();">
<em class="iconfont"></em>标签
</a>
</li>
</ul>
<div id="tupianqu">
<span class="ziti">本地上传</span>
<input id="tupian_btn" name="tupian_btn" type="file" accept="image/gif,image/jpeg,image/jpg,image/png" onchange="selectFile();" />
</div>
<button id="ptext_btn" type="submit">发布</button>
</form>
<iframe id="iframe_userInterface" name="iframe_userInterface" style="display: none;"></iframe>
3.js里获取文本代码如下:
$("#iframe_userInterface").load(function(){
var text = $(this).contents().find("body").text();//获取iframe里的内容
console.log(text);//打印iframe页面的内容
}
})
可以利用text来进行验证
后台要接收form表单传过去的数据,并且利用GSON将返回值传回到iframe里,
代码:
@WebServlet("/PublishPostingsServlet")
@MultipartConfig // 标识Servlet支持文件上传
public class PublishPostingsServlet extends HttpServlet {
private static final long serialVersionUID = 1L;// 主要用于版本控制
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 设置数据的编码方式为utf-8
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
// 返回的是项目在tomcat中的实际发布运行的根路径
String savePath = request.getServletContext().getRealPath("/picture");
Part part = request.getPart("tupian_btn");
String header = part.getHeader("content-disposition");// 获取请求头--form-data; name="tupian_btn"; filename=""
String fileName = getFileName(header);// 获取文件名
System.out.println("文件名:" + fileName);
part.write(savePath + File.separator + fileName);// 获取文件类型
/*判断登录状态*/
String id = null;
int result = 0;// 返回给前端的结果
HttpSession session = request.getSession();
id = (String) session.getAttribute("Account");
System.out.println("session里的id:" + id);
if (id == null) {
result = 4;// 当id为空的时候,登录失效,返回4
}
String ptext = request.getParameter("ptext");// 获取前台页面传递的参数
String label = Tools.getTable(ptext);
String ptime = Tools.getTime();
while (result == 0) {
result = PostingsService.publishPostings(id, ptext, ptime, label, fileName);// result接收数据在处理的结果1或2或3
}
Gson gson = new Gson();
String postinfsInfo = gson.toJson(result);// 定义postingsInfo存放GSON要传回的数据
response.getWriter().write(postinfsInfo);// 返回数据
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);// 调用doGet
}
}