Struts 2提交form表單執行action後不跳轉(ajax)
阿新 • • 發佈:2019-01-23
今日寫專案寫到一個商品加入購物車功能,原本設計是點選按鈕之後,儲存資料,並彈出一個div告知使用者新增成功,頁面不跳轉,看似很簡單的功能,卻在“不跳轉”這點上卡住,我不想跳轉咋就這麼難呢?查了很多資料,知道了要用ajax,因為本人愚鈍,並沒有能夠解決我的小問題,一度想要放棄,特別感謝熊世唯同學不耐其煩的指導,讓我解決了這個小難題
本篇部落格旨在還沒有深入理解ajax的情況下,實現一個提交form表單後不跳轉的功能(因為本人也完全不懂)
1.匯入jQuery
這個很簡單,在jsp頁面head里加上
<script src="http://cdn.static.runoob.com/libs/jquery/1.10.2/jquery.min.js" ></script>
2.寫提交表單的函式
同樣也是在jsp里加上js程式碼
<script type="text/javascript">
function addcart(){
var goodID = "<s:property value='goods.goodsId'/>";
var num = $('#num').val();
$.get("insertCart?goodsId="+goodID+"&goodsNum="+num,function(data,status) {
document.getElementById("insertCartMessage").style.display="block";
});
return false;
}
</script>
上面insertCart
是我action的名字,insertCartMessage
則是顯示提示資訊div的id
簡化之後應該是這樣
<script type="text/javascript">
function ajaxsubmit(){
$.get("actionname" ,function(data,status){
});
return false;
}
</script>
如果要用post方法的話就是
$.post("actionname", "", function(message, status) {
3.為提交按鈕指定函式
這個簡單,就是點選後執行上面的函式就行了。我用的是a標籤:
<a href="javascript:addcart();">加入購物車</a>
4.更改action
- 加一個InputStream,併為其提供getter和setter方法
- 在execute()中為inputStream設定值,這裡可以按需求設定,比如”新增成功”/”新增失敗”什麼的
package org.action;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import com.opensymphony.xwork2.ActionSupport;
public class InsertCartAction extends ActionSupport{
private InputStream inputStream;
public InputStream getInputStream() {
return inputStream;
}
public void setInputStream(InputStream inputStream) {
this.inputStream = inputStream;
}
public String execute() throws Exception {
//System.out.println("正在新增入購物車");
String str = "";
inputStream = new ByteArrayInputStream(str.getBytes("UTF-8"));
return SUCCESS;
}
}
5.配置struts.xml
在struts配置檔案中,result的type設為stream。其中包含兩個引數,第一個是contentType,表示響應的型別,如果有中文的話最好設定一下編碼,第二個引數是用來指定Action中的對應的輸入流,它的預設值就是inputStream,所以可以省略。
<action name="insertCart" class="org.action.InsertCartAction">
<result name="success" type="stream">
<param name="contentType">text/html; charset=utf-8</param>
<param name="inputName">inputStream</param>
</result>
</action>