1. 程式人生 > >關於SSH專案中a標籤提交action後執行兩次的問題

關於SSH專案中a標籤提交action後執行兩次的問題

             首先簡述一下問題,專案時SSH框架搭的,是一個小例子,什麼樣式都沒有,只是使用<s:iterator>將值棧中的資料遍歷出來,使用<a>標籤來提交修改和刪除,但是遇到了action執行兩次的問題。通過debug除錯。firebug除錯,和在瀏覽器輸入條中手動刪除資料最終確定是<a>標籤造成的提交兩次。暫時不清楚造成的原理是什麼,但是提供一個簡單的解決方案,供參考,有解決的朋友也可以相互探討,謝謝。

      jsp程式碼(提交兩次的)

<table width="860" border="1" cellPadding="4" cellSpacing="0"style="border-collapse: collapse" BorderColor="#808080">
		<tr>
	   	        <th width="50" scope="col">編號</th>
			<th width="70" scope="col">使用者名稱</th>
			<th width="70" scope="col">許可權名稱</th>
			<th width="70" scope="col">性別</th>
			<th width="70" scope="col">郵箱</th>
			<th width="70" scope="col">電話</th>
			<th width="70" scope="col">建立時間</th>
			<th width="70" scope="col">修改</th>
			<th width="70" scope="col">刪除</th>
		</tr>
		<s:iterator value="user" var="u" status="u_index">
			<tr>
				<td><s:property value="#u_index.index+1" /></td>
				<td><s:property value="#u.name" /></td>
				<td><s:property value="#u.remark" /></td>
				<td>
				<s:if test="#u.sex=='0'.toString()">
				女
				</s:if><s:elseif test="#u.sex=='1'.toString()">
				男
				</s:elseif><s:else>
					
				</s:else>	
				</td>
				<td><s:property value="#u.email" /></td>
				<td><s:property value="#u.tel" /></td>
				<td>
				<s:property	value="#u.createdate" /> 
                            <!--  註釋掉的按格式顯示時間程式碼開始時候可以使用。但是修改除錯程式之後不知道為什麼不起作用了
                               暫時註釋,方法沒有問題,-->
                           <!-- <s:property value="%{getText('{0,date,yyyy-MM-dd}',{#u.createdate})}" />  -->
				</td>
                              <!--從其他地方找了些帖子看,好多說是有多個a標籤或影象的標籤影響,所以先刪掉只保留刪除-->
                             <td>修改
                              </td>
				<td>
                                       <!--a標籤提交action造成了兩次提交,-->
                                      <a href="delUserById.action?id=<s:property value="#u.id" />">刪除</a> 
					
				</td>
			</tr>
		</s:iterator>
	</table>
struts.xml的配置action程式碼
                <action name="delUserById" class="userAction" method="delUserById">
			<result name="delUser"type="dispatcher">main.jsp</result>
			<result name="error">main.jsp</result>
		</action>
action的程式碼
	public String delUserById(){
		
		id = Integer.parseInt(ServletActionContext.getRequest().getParameter("id"));
		System.out.println(id);
		//現將後臺的刪除邏輯注掉只執行列印語句,獲得兩次id結果
		//users = userService.delUserById(id);
		
		//if(users.isEmpty()){
			
		//	return "error";
			
		//}else{
		//	ActionContext.getContext().put("user", users);
			
		return "delUser";
		//}
		
	}

      解決方案:將a便籤的提交換成button提交,換成button提交的後果就是新增點選事件onclick()

將“刪除”的程式碼改為

 <input type="button" value = "刪除" onclick="del(<s:property value="#u.id" />)"/> 
       js程式碼為
<script type="text/javascript">
function del(id){
	var  url='delUserById?id='+id;
	//alert(url);
	window.location=url;
}
</script>

      這樣修改後完全正常,不會在出現提交兩次,如果用a標籤提交action,一定要檢查類似這樣的程式碼<a href="">最好改成

<a href="#">同時也要之一圖片地址程式碼<src="">還有標頭檔案中的link.

      總之,使用a標籤比較簡單。但是出錯後確實詭異。