Client-side/SCRIPT
자바스크립트 Form 생성하여 Post 전송
그곰
2011. 11. 15. 11:34
보통 내가 자바스크립트를 통해 url과 parameter를 전송할때에 쓰는 스크립트는 아래와 같이 GET방식을 이용한 전송을 사용한다.
이러한 번거로운 작업을 피하기 위해 아래 소스를 찾게 되었다.참고하여 실 작업에 반영하도록 하자.
document.location.href="http://example.com/a.php?q=a";
하지만 어떤 경우에는 POST 방식의 전송을 써야하는 경우가 발생하는데 아래와 같이 <form>태그를 이용하려면 값을 입력하고 전송해주는 스크립트를 만들고 <form>를 선언해놔야 사용할 수가 있다.
<form action="http://example.com/a.php" method="POST"> <input type="hidden" name="q" value="a"> </form>
/* * path : 전송 URL * params : 전송 데이터 {'q':'a','s':'b','c':'d'...}으로 묶어서 배열 입력 * method : 전송 방식(생략가능) */ function post_to_url(path, params, method) { method = method || "post"; // Set method to post by default, if not specified. // The rest of this code assumes you are not using a library. // It can be made less wordy if you use one. var form = document.createElement("form"); form.setAttribute("method", method); form.setAttribute("action", path); for(var key in params) { var hiddenField = document.createElement("input"); hiddenField.setAttribute("type", "hidden"); hiddenField.setAttribute("name", key); hiddenField.setAttribute("value", params[key]); form.appendChild(hiddenField); } document.body.appendChild(form); form.submit(); }실제로 구동시킬 때 입력 예제
post_to_url('http://example.com/', {'q':'a'});