springmvc框架下jquery的ajax使用
文章目錄
前臺
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>上架商品-ajax</title> <!-- Tell the browser to be responsive to screen width --> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Font Awesome --> <link rel="stylesheet" href="${pageContext.request.contextPath}/conf1/css/font-awesome.min.css"> <!-- Ionicons --> <link rel="stylesheet" href="${pageContext.request.contextPath}/conf1/css/ionicons.min.css"> <!-- Theme style --> <link rel="stylesheet" href="${pageContext.request.contextPath}/conf1/dist/css/adminlte.min.css"> <!-- Google Font: Source Sans Pro --> <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,400i,700" rel="stylesheet"> </head> <script type="text/javascript"> function getRealPath(){ //獲取當前網址,如: http://localhost:8083/myproj/view/ahha.jsp var curWwwPath=window.document.location.href; //獲取主機地址之後的目錄,如: myproj/view/ahha.jsp var pathName=window.document.location.pathname; var pos=curWwwPath.indexOf(pathName); //獲取主機地址,如: http://localhost:8080 var localhostPaht=curWwwPath.substring(0,pos); //獲取帶"/"的專案名,如:/ahha var projectName=pathName.substring(0,pathName.substr(1).indexOf('/')+1); //得到了 伺服器名稱和專案名稱 var realPath=localhostPaht+projectName; return realPath; } function downProduct(id){ var params = { id : id }; alert(JSON.stringify(params)); var nowUrl=getRealPath()+"/admin/downProductAjax.do"; $.ajax({ type : "post", url : "./downProductAjax.do",//訪問路徑 dataType : "json", contentType : "application/json", data : JSON.stringify(params), timeout : 5000, error : alertSuccess, global : false, success : alertSuccess,//查詢成功處理函式 }); } function alertSuccess(result) { // 處理返回的資料result alert(result.info); alert(result.product.name); //通過處理result返回的結果集顯示到頁面 } </script> <body> <div class="wrapper"> <jsp:include page="side_admin.jsp"></jsp:include> <!-- Content Wrapper. Contains page content --> <div class="content-wrapper"> <!-- Content Header (Page header) --> <section class="content-header"> <div class="container-fluid"> <div class="row mb-2"> <div class="col-sm-6"> <h1>下架商品</h1> </div> </div> </div><!-- /.container-fluid --> </section> <!-- Main content --> <section class="content"> <div class="row"> <div class="col-12"> <div class="card"> <div class="card-header"> <h3 class="card-title">商品列表</h3> </div> <!-- /.card-header --> <div class="card-body"> <table id="example1" class="table table-bordered table-striped"> <thead> <tr> <th>商品編號</th> <th>賣家名字</th> <th>商品名字</th> <th>商品種類</th> <th>商品價格</th> <th>操作</th> </tr> </thead> <tbody> <c:forEach items="${products }" var="product" > <tr> <td>${product.id }</td> <td>${product.sellerName }</td> <td>${product.name }</td> <td>${product.categoryName }</td> <td>${product.price }</td> <td> <button type="button" class="btn btn-primary" onclick="downProduct(${product.id })">下架</button> </td> </tr> </c:forEach> </tbody> </table> </div> <!-- /.card-body --> </div> <!-- /.card --> </div> <!-- /.col --> </div> </section> <!-- /.content --> </div> <!-- /.content-wrapper --> <footer class="main-footer"> <div class="float-right d-none d-sm-block"> <b></b> </div> <strong>Copyright © 2018 <a href="#">中央財經大學</a>.</strong> All rights reserved. </footer> <!-- Control Sidebar --> <aside class="control-sidebar control-sidebar-dark"> <!-- Control sidebar content goes here --> </aside> <!-- /.control-sidebar --> </div> <!-- ./wrapper --> <input id="PageContext" type="hidden" value="${pageContext.request.contextPath}" /> <!-- jQuery --> <script src="${pageContext.request.contextPath}/conf1/plugins/jquery/jquery.min.js"></script> <!-- Bootstrap 4 --> <script src="${pageContext.request.contextPath}/conf1/plugins/bootstrap/js/bootstrap.bundle.min.js"></script> <!-- FastClick --> <script src="${pageContext.request.contextPath}/conf1/plugins/fastclick/fastclick.js"></script> <!-- AdminLTE App --> <script src="${pageContext.request.contextPath}/conf1/dist/js/adminlte.min.js"></script> <!-- AdminLTE for demo purposes --> <script src="${pageContext.request.contextPath}/conf1/dist/js/demo.js"></script> </body> </html>
controller程式碼
@ResponseBody @RequestMapping(value="/downProductAjax") public Map<String, Object> downProductAjax(@RequestBody Map<String,Object> map1)throws Exception{ System.out.println("ok1"); System.out.println(map1.get("id").toString()); Integer productId=(Integer)map1.get("id"); adminService.downProduct(productId); Product product=adminService.getProductById(productId); Map<String, Object> map =new HashMap<String, Object>(); map.put("info", "商品"+product.getName()+"上架成功"); map.put("product", product); map.put("info", "進入成功"); return map; }
關鍵點
1 前臺編寫函式,傳遞資料,進行ajax
function downProduct(id){ var params = { id : id }; alert(JSON.stringify(params)); var nowUrl=getRealPath()+"/admin/downProductAjax.do"; $.ajax({ type : "post", url : "./downProductAjax.do",//訪問路徑 dataType : "json", contentType : "application/json", data : JSON.stringify(params), timeout : 5000, error : alertSuccess, global : false, success : alertSuccess,//查詢成功處理函式 }); } function alertSuccess(result) { // 處理返回的資料result alert(result.info); alert(result.product.name); //通過處理result返回的結果集顯示到頁面 }
2 Params為js的物件,傳遞過去轉為json字串JSON.stringify(params),
3 傳遞到後臺的路徑
本頁面的路徑為
http://localhost:8080/campus_second_ssh/admin/showCanSellProductsAjax.do
url : “./downProductAjax.do”,//訪問路徑
傳遞的路徑實際為
http://localhost:8080/campus_second_ssh/admin/downProductAjax.do
用./xxx現在可以
如果是
url : “././admin/downProductAjax.do”,//訪問路徑
(0 ms) [http-nio-8080-exec-4] WARN : org.springframework.web.servlet.PageNotFound#noHandlerFound :
No mapping found for HTTP request with URI
[/campus_second_ssh/admin/admin/downProductAjax.do] in DispatcherServlet with name ‘mvc’
相當於兩次./只有一次的效果
如果是
url : “/admin/downProductAjax.do”
後臺springmvc沒有反應,可能路徑沒有到/campus_second_ssh/裡來
如果是
url : “/campus_second_ssh/admin/admin/downProductAjax.do”,//訪問路徑
(0 ms) [http-nio-8080-exec-9] WARN : org.springframework.web.servlet.PageNotFound#noHandlerFound :
No mapping found for HTTP request with URI [
/campus_second_ssh/admin/admin/downProductAjax.do]
in DispatcherServlet with name ‘mvc’
這次多加了admin,應該是可以的
如果是
url : “/campus_second_ssh/admin/downProductAjax.do”,//訪問路徑
成功
得到結論,如果是同一個大的controller下的,可以用./xxx.do
如果不是,可以用/專案名/xxx/xxx.do
4. java後臺controller入參
@ResponseBody
@RequestMapping(value="/downProductAjax")
public Map<String, Object> downProductAjax(@RequestBody Map<String,Object> map1)throws Exception{
System.out.println("ok1");
System.out.println(map1.get("id").toString());
入參的關鍵是@RequestBody Map<String,Object> map1
必須有requestbody標籤
這個物件可以是一個string object的map
也可以是一個string
也可以是一個po類,
springmvc通過requestbody,將json字串轉為map或者單個的string或者封裝為po類
但是經過測試,如果是int型別不知道為什麼無法進入,留待以後研究
5java後臺出參和ajax返回結果
Map<String, Object> map =new HashMap<String, Object>();
map.put("info", "商品"+product.getName()+"上架成功");
map.put("product", product);
map.put("info", "進入成功");
return map;
首先,返回時必須要有responsebody標籤
然後返回時可以返回一個map,將object裝在map中,這樣比較好
然後ajax根據返回的物件
success : alertSuccess,//查詢成功處理函式
});
}
function alertSuccess(result) {
// 處理返回的資料result
alert(result.info);
alert(result.product.name);
//通過處理result返回的結果集顯示到頁面
}
對返回結果進行改變