prosource

Jquery AJAX를 사용하여 HTML 양식 제출

probook 2023. 3. 29. 21:35
반응형

Jquery AJAX를 사용하여 HTML 양식 제출

예를 사용하여 AJAX를 사용하여 HTML 폼을 제출하려고 합니다.

내 HTML 코드:

<form id="formoid" action="studentFormInsert.php" title="" method="post">
    <div>
        <label class="title">First Name</label>
        <input type="text" id="name" name="name" >
    </div>
    <div>
        <label class="title">Name</label>
        <input type="text" id="name2" name="name2" >
    </div>
    <div>
        <input type="submit" id="submitButton"  name="submitButton" value="Submit">
    </div>
</form>

내 스크립트:

<script type="text/javascript">
    $(document).ready(function() { 
        $('#formoid').ajaxForm(function() { 
            alert("Thank you for your comment!"); 
        }); 
    });
</script>

이 방법은 동작하지 않습니다.경보 메시지도 표시되지 않습니다.또, 송신시에 다른 페이지로 리다이렉트 하고 싶지 않습니다.경보 메시지를 표시하고 싶을 뿐입니다.

간단한 방법이 있나요?

추신: 저는 몇 개의 필드가 있습니다.예를 들어 두 개의 필드를 예로 들겠습니다.

AJAX의 간단한 설명

AJAX는 단순히 비동기 JSON 또는 XML입니다(대부분 새로운 상황에서는 JSON).우리는 비동기 작업을 하고 있기 때문에 사용자에게 더 즐거운 UI 경험을 제공할 것입니다.이 경우 AJAX를 사용하여 FORM을 제출합니다.

간단하게 4가지 일반적인 웹 액션이 있습니다.GET,POST,PUT,그리고.DELETE; 이것들은 와 직접 대응합니다.SELECT/Retreiving DATA,INSERTING DATA,UPDATING/UPSERTING DATA,그리고.DELETING DATA. 기본 HTML/ASP.인터넷 웹폼/PHP/Python 또는 기타formaction은 POST 액션인 "submit"입니다.이 때문에, 이하에서는 모두 POST 의 실행 방법에 대해 설명합니다.단, http에서는 다른 액션이 필요할 수 있으며, 이 기능을 이용할 수도 있습니다..ajax.

고객 전용 코드(코드 코멘트에 기재되어 있음):

/* attach a submit handler to the form */
$("#formoid").submit(function(event) {

  /* stop form from submitting normally */
  event.preventDefault();

  /* get the action attribute from the <form action=""> element */
  var $form = $(this),
    url = $form.attr('action');

  /* Send the data using post with element id name and name2*/
  var posting = $.post(url, {
    name: $('#name').val(),
    name2: $('#name2').val()
  });

  /* Alerts the results */
  posting.done(function(data) {
    $('#result').text('success');
  });
  posting.fail(function() {
    $('#result').text('failed');
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<form id="formoid" action="studentFormInsert.php" title="" method="post">
  <div>
    <label class="title">First Name</label>
    <input type="text" id="name" name="name">
  </div>
  <div>
    <label class="title">Last Name</label>
    <input type="text" id="name2" name="name2">
  </div>
  <div>
    <input type="submit" id="submitButton" name="submitButton" value="Submit">
  </div>
</form>

<div id="result"></div>


문서

jQuery 웹사이트에서$.post문서를 참조해 주세요.

: Ajax 요청을 사용하여 양식 데이터 전송

$.post("test.php", $("#testform").serialize());

: ajax를 사용하여 폼을 투고하고 결과를 div에 넣습니다.

<!DOCTYPE html>
<html>
    <head>
        <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    </head>
    <body>
        <form action="/" id="searchForm">
            <input type="text" name="s" placeholder="Search..." />
            <input type="submit" value="Search" />
        </form>
        <!-- the result of the search will be rendered inside this div -->
        <div id="result"></div>
        <script>
            /* attach a submit handler to the form */
            $("#searchForm").submit(function(event) {

                /* stop form from submitting normally */
                event.preventDefault();

                /* get some values from elements on the page: */
                var $form = $(this),
                    term = $form.find('input[name="s"]').val(),
                    url = $form.attr('action');

                /* Send the data using post */
                var posting = $.post(url, {
                    s: term
                });

                /* Put the results in a div */
                posting.done(function(data) {
                    var content = $(data).find('#content');
                    $("#result").empty().append(content);
                });
            });
        </script>
    </body>
</html>

중요사항

OAuth를 사용하지 않거나 최소한 HTTPS(TLS/SSL)를 사용하지 않는 경우 보안 데이터(신용 카드 번호, SSN, PCI, HIPAA 또는 로그인 관련 정보)에 이 방법을 사용하지 마십시오.

var postData = "text";
      $.ajax({
            type: "post",
            url: "url",
            data: postData,
            contentType: "application/x-www-form-urlencoded",
            success: function(responseData, textStatus, jqXHR) {
                alert("data saved")
            },
            error: function(jqXHR, textStatus, errorThrown) {
                console.log(errorThrown);
            }
        })

$('FORM').serialize()는 사용하기 쉽지만 파일 입력/업로드에서는 작동하지 않습니다.

이 조작은 유효합니다.

<form id="myform">
   <input type="file" name="somefile">
   <button type="submit">Submit</button>
</script>

// jquery.form.min.js
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.form/4.3.0/jquery.form.min.js">

<script>
// register form for ajax
$('#myform').ajaxForm(function(submit_response) {
    console.log(submit_response);
});
</script>

언급URL : https://stackoverflow.com/questions/16323360/submitting-html-form-using-jquery-ajax

반응형