Ajaxを利用して入力フォームの内容を自動保存する
人力検索はてなで質問されていたので、軽く作ってみた。
入力フォームに入力した内容を5分おきに自動保存(自動登録?)… - 人力検索はてな
HTML(クライアント)側
<HTML> <HEAD> <TITLE>データ自動保存サンプル</TITLE> <META http-equiv=Content-Style-Type content=text/css> <META http-equiv=Content-Script-Type content=text/javascript> <meta http-equiv="Content-Type" content="text/html; charset=SHIFT_JIS"> <script type="text/javascript"> <!-- function init(){ setInterval("save()",1000*5);//5秒ごとにsaveメソッドを呼び出す } //サーバー側のデータ保存処理を呼び出す function save() { httpObj = createXMLHttpRequest(); httpObj.open("POST", "/test/save.do",false); //Strutsアクションを指定 httpObj.setRequestHeader("content-type","application/x-www-form-urlencoded;charset=UTF-8"); httpObj.onreadystatechange = function() { //サーバ側の処理終了 if (httpObj.readyState==4) { alert('保存完了'); } } //フォームの入力データを送信 httpObj.send("address=" + encodeURI(document.forms[0].address.value) + "&subject="+encodeURI(document.forms[0].subject.value)); } // XMLHttpRequestオブジェクトを生成 function createXMLHttpRequest(){ if(window.XMLHttpRequest) { httpObj = new XMLHttpRequest(); } else if(window.ActiveXObject) { try { httpObj = new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) { httpObj = new ActiveXObject("Microsoft.XMLHTTP"); } } return httpObj; } --> </script> </HEAD> <BODY onload="init()"> <form> <input type="text" name="address" ></input> <input type="text" name="subject" ></input> </form> </BODY> </HTML>
サーバ側
今回はJavaでStrutsを利用し作成した。ActionFormやフォームの内容をDBへ登録する処理は割愛。
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; public class SaveAction extends Action { public ActionForward execute(ActionMapping map, ActionForm frm, HttpServletRequest request, HttpServletResponse response) { //ここでアクションフォームから入力内容を受け取りデータベースへ保存する。 return null;//nullを返す。 } }