2012-12-12 5 views
1

나는자바 스크립트로 제출 양식에서 정보를 얻으려면 어떻게해야합니까?

<form name="loginForm" method="POST"> 
    Username: <input type="text" name="username" value="" /> 
    <br /> 
    Password: <input type="password" name="password" value="" /> 
    <input type="submit" name="submitButton" /> 
</form> 

는 어떻게 제출 버튼을 눌렀을 후 위의 정보를 가지고 가는가 형태를 가지고 있고, 데이터 말했다 뭔가를합니까? 예 :

<script> 
    function checkLogin(){ 
    //some code here 
    } 
</scipt> 

정말 버튼을 사용하는 방법을 알고 싶습니다. onClick이 아닙니다.

+1

음,이 서버로 이동합니다. 이것이 원하는 것이 아니라면 onClick의 문제점은 무엇입니까? – RonaldBarzell

답변

3

는 태그의 onsubmit 이벤트를 사용

HTML :

<form name="loginForm" method="POST" onsubmit="checkLogin()"> 
    Username: <input type="text" name="username" value="" /> 
    <br /> 
    Password: <input type="password" name="password" value="" /> 
    <input type="submit" name="submitButton" /> 
</form> 

스크립트 : 당신은 그냥 제출 사용하는 경우

function checkLogin(){ 
    // If you return "false" it will stop the form from being submitted 
} 
2

양식에 대해 onsubmit 함수를 지정할 수 있습니다. 같은 함수에서 다음

<form name="loginForm" method="POST" onsubmit="checkLogin()"> 

, 뭔가 :

function checkLogin() { 
    var username = document.forms["loginForm"]["username"]; 
    // validate the form. Return false and the form will not be posted to server. 
} 
+0

또한 checkLogin의 반환 값은 요청이 서버로 전송되는지 여부를 결정합니다. 양식이 서버에 게시되지 않도록하려면 false를 반환합니다. – BeWarned

1

당신은 다음과 같은 방법으로 $ .post를 사용합니다 {

$.post(URL_TO_YOUR_SCRIPT, { username: $("#username").val(), 
    password: $("#password).val() }, 
    function(data) { 
      alert(data); 
    }); 

이를 달성하기 위해, 당신은 ID의의를 제공해야합니다 입력란에

<input type="text" name="username" id="username" /> 
<input type="password" name="password" id="password" /> 

건배!

+0

이것은 jQuery 응답이며 OP는 그것을 사용하지 못했습니다. – SReject

+0

$ .post를 사용하기 위해 jQuery.js가 필요하다는 점을 잊어 버렸습니다. –

+0

또한 페이지를 새로 고침하고 작업 페이지로 리디렉션하지 않으려면 제출 버튼에 대한 클릭 이벤트를 만들 수 있습니다. $ ('input [type = "submit"]'). live ('click', function (e) { e.preventDefault(); checkLogin(); }); –

관련 문제