js代码
$(function() { //初始化ajaxForm $('#upForm').ajaxForm({ dataType:'text', type:'POST', clearForm:true, // clear all form fields after successful submit resetForm:true, // reset the form after successful submit beforeSubmit:check, success:function(data) { alert(data); } }); function check(formData, jqForm, options) { //加入一些自定义的验证 //返回false阻止可以表单提交 } });
返回json接收不到,将dataType设置为text
html
<form id="upForm" method="POST" enctype="MULTIPART/FORM-DATA" action="saveCommanInfo.action" target="hidden_frame">
<iframe name='hidden_frame' id="hidden_frame" style='display: none'></iframe>
<input name="name" id="name"/>
<input type="file" name="photo" id="photo"/>
<input type="submit" value="提交表单"/>
</form>
Action
public String save() throws Exception {
//处理上传
try {
..........
String ajaxResult="上传成功!";
//将提示信息返回前台
response.setContentType("text/html; charset=utf-8");
response.setHeader("Cache-Control", "no-cache");
PrintWriter out = response.getWriter();
out.write("<script>alert('"+ajaxResult+"')</script>");
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
throw new GlobalException(e);
}
// 不做跳转,返回none,返回null也可以
return NONE;
}
Action配置
<package name="system" extends="json-default"> <action name="save" class="systemAction" method="save"> <result type="json"> <!-- 返回html文本 --> <param name="contentType">text/html</param> <!-- 返回的提示信息 --> <param name="root">ajaxResult</param> </result> </action> </package>
注意要继承json-default,页面上要引入jquery和jquery.form