Ajax使用jQuery与后台交互
- Ajax使用jQuery与后台交互
- 前言
- Ajax
- Ajax的优点
- XmlHttpRequest对象
- 数据篇
- jquery-form的方式提交数据
- 自定义数据篇
- 自定义上传的数据
- 文件篇
- 前台使用ajaxuploadjs对文件进行上传
- 后台使用commons-fileuploadjar上传文件
- MyFilejava文件
- UploadUtiljava工具
- JAR包
- 项目下载路径
- 后言
前言
Ajax
Ajax就是异步JavaScript and XML缩写。
Ajax的优点
- 通过异步模式,提高用户体验
- 优化浏览器与服务器之间传输,按需索取
- Ajax引擎是在客户端运行的,承担了一部分本来由服务器承担的工作
XmlHttpRequest对象
Ajax的核心就是XmlHttpRequest对象。通过XMLHttpRequest对象,Web开发人员可以在页面加载以后进行页面的局部更新。
数据篇
jquery-form的方式提交数据
- 前端数据
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Ajax提交表单</title>
</head>
<body>
<form action="form_submit" method="post" id="myform" name="myform">
<input type="text" id="mytext" name="mytext" value="text"/>
<button type="button" id="mybutton" name="mybutton">提交</button>
</form>
<!-- 导入必须的文件 -->
<script type="text/javascript" src="/MyAjax/resource/js/jquery-1.9.1.js"></script>
<script type="text/javascript" src="/MyAjax/resource/js/jquery-form.js"></script>
<script type="text/javascript">
<!--向后台发送post请求-->
$(document).ready(function() {
$("#mybutton").click(function () {
$.ajax({
type:"POST",//提交请求的方式
cache:true,//是否有缓存
url:"form_submit",//访问servlet的路径
dataType:"json",//没有这个,将把后台放会的json解析成字符串
data:$('#myform').serialize(),//把内容序列化
async:true,//是否异步
error:function(request) {//请求出错
alert("出错");
},
success:function(data) {//获得返回值
alert(data["mytext"]);
}
})
});
});
</script>
</body>
</html>
2.后台代码
package com.chen.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONObject;
/**
*
* @author CHEN
* @description 提交表单
* @导包:json-lib-2.2.2-jdk15.jar\ezmorph-1.0.4.jar
*/
@WebServlet("/form_submit")
public class FormSubmit extends HttpServlet{
/**
*
*/
private static final long serialVersionUID = -8615452472287083708L;
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
System.out.println(req.getParameter("myid"));
String mytext=req.getParameter("mytext");
JSONObject jObject=new JSONObject();
jObject.put("mytext", mytext);
PrintWriter out=resp.getWriter();
out.print(jObject);
out.close();
}
}
自定义数据篇
自定义上传的数据
有时候,我们所需的内容并不总是在一个表单中,这时候,我们就需要进行拼接,以下提供了两种拼接的方法。
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Ajax提交表单</title>
</head>
<body>
<!-- 共有的某行数据 -->
<input type="hidden" id="myid" name="myid" value="123456">
<form action="form_submit" method="post" id="myform" name="myform">
<input type="text" id="mytext" name="mytext" value="text"/>
<button type="button" id="mybutton" name="mybutton">提交</button>
</form>
<!-- 导入必须的文件 -->
<script type="text/javascript" src="/MyAjax/resource/js/jquery-1.9.1.js"></script>
<script type="text/javascript" src="/MyAjax/resource/js/jquery-form.js"></script>
<script type="text/javascript">
<!--向后台发送post请求-->
$(document).ready(function() {
$("#mybutton").click(function () {
//准备数据
var myform=$('#myform').serialize();//表单序列化
//myform += "&myid="+encodeURIComponent($('#myid').val());//方法1:按格式拼接
myform+= "&"+$('#myid').serialize();//方法2:拼接上需要的字符串
$.ajax({
type:"POST",//提交请求的方式
cache:true,//是否有缓存
url:"form_submit",//访问servlet的路径
dataType:"json",//没有这个,将把后台放会的json解析成字符串
data:myform,//把内容序列化
async:true,//是否异步
error:function(request) {//请求出错
alert("出错");
},
success:function(data) {//获得返回值
alert(data["mytext"]);
}
})
});
});
</script>
</body>
</html>
方法1:按格式拼接
myform += “&myid=”+encodeURIComponent($(‘#myid’).val());
方法2:拼接上需要的字符串
myform+= “&”+$(‘#myid’).serialize();
后台的接收还是一样的。
文件篇
前台使用ajaxupload.js对文件进行上传
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Ajax提交表单</title>
</head>
<body>
<!-- 共有的某行数据 -->
<input type="hidden" id="myid" name="myid" value="123456"/>
<form action="form_submit" method="post" id="myform" name="myform" >
<input type="text" id="mytext" name="mytext" value="text"/>
<button type="button" id="mybutton" name="mybutton">提交</button>
</form>
<br/>
<form action="#" enctype="multipart/form-data">
<input type="file" id="myfile" name="myfile"/>
<button type="button" id="myfilebutton" name="myfilebutton">上传</button>
</form>
<div id="mydiv"></div>
<!-- 导入必须的文件 -->
<script type="text/javascript" src="/MyAjax/resource/js/jquery-1.9.1.js"></script>
<script type="text/javascript" src="/MyAjax/resource/js/jquery-form.js"></script>
<script type="text/javascript" src="/MyAjax/resource/js/ajaxupload.js"></script>
<script type="text/javascript">
/**
向后台发送post请求
**/
$(document).ready(function() {
$("#mybutton").click(function () {
//准备数据
var myform=$('#myform').serialize();//表单序列化
//myform += "&myid="+encodeURIComponent($('#myid').val());//方法1:按格式拼接
myform+= "&"+$('#myid').serialize();//方法2:拼接上需要的字符串
$.ajax({
type:"POST",//提交请求的方式
cache:true,//是否有缓存
url:"form_submit",//访问servlet的路径
dataType:"json",//没有这个,将把后台放会的json解析成字符串
data:myform,//把内容序列化
async:true,//是否异步
error:function(request) {//请求出错
alert("出错");
},
success:function(data) {//获得返回值
alert(data["mytext"]);
}
})
});
});
/**
向后台发送文件
**/
$(document).ready(function() {
$('#myfilebutton').click(function() {
$.ajaxFileUpload({
url:"file_submit",//后他处理的路径
secureuri:false,//是否需要安全协议,一般置为false
fileElementId:'myfile',//文件id
dataType:"json",//返回类型,默认string
success:function(data,status) {
alert(data["message"]);//返回信息
//拼接
var a=document.createElement("a");
a.href=data['allUrl'];
a.innerHTML=data['fileName'];
var mydiv=document.getElementById('mydiv');
mydiv.appendChild(a);
},
error:function(data,status,e) {//返回信息
alert('出错了');
}
});
return false;
});
});
</script>
</body>
</html>
后台使用commons-fileupload.jar上传文件
package com.chen.servlet;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileUploadException;
import net.sf.json.JSONObject;
import com.chen.model.MyFile;
import com.chen.util.UploadUtil;
/**
*
* @author CHEN
* @description 上传文件
*/
@WebServlet("/file_submit")
public class FileSumbit extends HttpServlet{
/**
*
*/
private static final long serialVersionUID = -1868776810282017505L;
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
System.out.println("上传文件");
MyFile file=new MyFile(req.getServletContext().getRealPath("/resource/uploadTemp"),req.getServletContext().getRealPath("/resource/upload"));
UploadUtil uUtil=new UploadUtil();
String message="上传失败";
try {
message=uUtil.uploadfiFactoryle(file, req);
} catch (FileUploadException e) {
e.printStackTrace();
}
//返回的内容
PrintWriter out=resp.getWriter();
JSONObject jsonObject=new JSONObject();
jsonObject.put("message", message);
jsonObject.put("allUrl","http://"+InetAddress.getLocalHost().getHostAddress()+":"
+req.getLocalPort()+File.separator+req.getContextPath()+"/resource/upload/"+file.getFileName());
jsonObject.put("fileName", file.getFileName());
out.print(jsonObject);
out.close();
}
}
MyFile.java文件
package com.chen.model;
import java.io.File;
/**
*
* @author CHEN
*
*/
public class MyFile {
private File file;
private String fileName;//文件名
private String tempUrl;//缓存路径
private String saveUrl;//保存路径
private String allUrl;//文件全路径
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public MyFile() {
super();
}
public File getFile() {
return file;
}
public void setFile(File file) {
this.file = file;
}
public String getSaveUrl() {
return saveUrl;
}
public void setSaveUrl(String saveUrl) {
this.saveUrl = saveUrl;
}
public String getTempUrl() {
return tempUrl;
}
public void setTempUrl(String tempUrl) {
this.tempUrl = tempUrl;
}
public String getAllUrl() {
return allUrl;
}
public void setAllUrl(String allUrl) {
this.allUrl = allUrl;
}
public MyFile(String tempUrl, String saveUrl) {
super();
this.tempUrl = tempUrl;
this.saveUrl = saveUrl;
}
public MyFile(String saveUrl) {
super();
this.saveUrl = saveUrl;
}
}
UploadUtil.java工具
package com.chen.util;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.servlet.ServletRequestContext;
import com.chen.model.MyFile;
import java.util.List;
/**
*
* @author CHEN
* @description 上传文件的工具
*/
public class UploadUtil {
public String uploadfiFactoryle(MyFile file, HttpServletRequest request)
throws FileUploadException, IOException {
// 配置上传的属性
DiskFileItemFactory dfiFactory = new DiskFileItemFactory();
dfiFactory.setSizeThreshold(10 * 1024);
dfiFactory.setRepository(new File(file.getTempUrl()));
// 配置解析器
ServletFileUpload sfupLoad = new ServletFileUpload(dfiFactory);
sfupLoad.setHeaderEncoding("utf-8");
// 对请求进行解析
List<FileItem> filList = sfupLoad
.parseRequest(new ServletRequestContext(request));
// 文件名
String fileName = null;
String allUrl=null;
//for (FileItem item : filList) {
FileItem item = getUploadFileItem(filList);
if (item.isFormField()) {// 普通表单
return "文件错误";
} else {// file表单
fileName = item.getName();
System.out.println(fileName);
allUrl=file.getSaveUrl()+ File.separator + fileName;
FileOutputStream out = new FileOutputStream(allUrl);
InputStream in = item.getInputStream();
// 开始存入服务器端
byte[] buf = new byte[1024];
int len = 0;
while ((len = in.read(buf)) > 0)
out.write(buf, 0, len);
in.close();
out.close();
item.delete();// 删除临时文件
}
//}
file.setFileName(fileName);
file.setAllUrl(allUrl);
return "上传成功";
}
private FileItem getUploadFileItem(List<FileItem> list) {
for (FileItem fileItem : list) {
if(!fileItem.isFormField()) {
return fileItem;
}
}
return null;
}
}
JAR包