Ajax使用jQuery與後臺互動
Ajax使用jQuery與後臺互動
前言
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>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
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();
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
自定義資料篇
自定義上傳的資料
有時候,我們所需的內容並不總是在一個表單中,這時候,我們就需要進行拼接,以下提供了兩種拼接的方法。
<%@ 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
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
方法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>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 79
- 80
- 81
- 82
- 83
- 84
- 85
- 86
- 87
後臺使用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();
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
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;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
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;
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
- 26
- 27
- 28
- 29
- 30
- 31
- 32
- 33
- 34
- 35
- 36
- 37
- 38
- 39
- 40
- 41
- 42
- 43
- 44
- 45
- 46
- 47
- 48
- 49
- 50
- 51
- 52
- 53
- 54
- 55
- 56
- 57
- 58
- 59
- 60
- 61
- 62
- 63
- 64
- 65
- 66
- 67
- 68
- 69
- 70
- 71
- 72
- 73
- 74
- 75
- 76
- 77
- 78
JAR包
專案下載路徑
因為CSDN上傳檔案大小有限制,所以我已經把jar包去掉了,如果有需要在評論留下你的聯絡方式。
原始碼下載地址
後言
作為後臺人員,也應該懂點前端的東西,不是嗎?
- 上一篇命名規範
- 下一篇HttpClient模擬請求例項
相關文章
- jQuery|前後臺xml互動就靠它了jQueryXML
- Http(s)與後臺互動方式HTTP
- 筆記:前端與後臺互動筆記前端
- ajax與XML檔案互動XML
- jquery使用ajax讀取後臺資料在表格中顯示jQuery
- JQuery使用AJAXjQuery
- AJAX-前後端互動的藝術後端
- web互動方式---ajaxWeb
- Flex與後臺互動的幾種方法詳解Flex
- jquery ajax簡單使用jQuery
- 前後端資料互動(三)——ajax 封裝及呼叫後端封裝
- 簡單的使用者登入頁面與後臺資料庫的互動資料庫
- Ajax 資料非同步互動非同步
- jQuery學習(2)ajax()使用jQuery
- 前後端資料互動(二)——原生 ajax 請求詳解後端
- 原聲ajax與jquery ajax請求的區別jQuery
- 使用Jquery和Ajax的動態依賴選擇框jQuery
- ABAP Development Tool前後臺互動的原理dev
- jQuery AjaxjQuery
- jQuery - AJAXjQuery
- SpringMVC之ajax非同步互動SpringMVC非同步
- Jquery 和 Ajax的 使用方法jQuery
- jQuery.ajax的使用方法jQuery
- Winform中使用HttpClient與後端api服務進行互動ORMHTTPclient後端API
- jQuery Ajax應用與常用外掛jQuery
- Ajax請求後臺資料
- jquery ajax從後臺讀取的資料無法賦值給變數jQuery賦值變數
- 長連線在後臺和前臺之間的互動
- 使用jQuery 完成ajax 檔案下載jQuery
- Google AR 互動的開源與幕後Go
- jQuery.ajaxjQuery
- ajax +jquery 基本jQuery
- jQuery AJAX 方法jQuery
- jquery Ajax搭配jQuery
- jQuery.ajax()jQuery
- jQuery系列:AjaxjQuery
- JQuery中ajax的使用與快取問題的解決方法jQuery快取
- jquery的ajax請求servlet與響應jQueryServlet