developer tip

form.submit의 응답을 캡처하는 방법

optionbox 2020. 7. 30. 10:21
반응형

form.submit의 응답을 캡처하는 방법


다음 코드가 있습니다.

<script type="text/javascript">
        function SubmitForm()
        {

            form1.submit();
        }

        function ShowResponse()
        {

        }
</script>
.
.
.
<div>
    <a href="#" onclick="SubmitForm();">Click</a>
</div>

의 html 응답을 캡처하고 싶습니다 form1.submit. 어떻게해야합니까? form1.submit 메소드에 콜백 함수를 등록 할 수 있습니까?


일반 자바 스크립트로는이 작업을 쉽게 수행 할 수 없습니다. 양식을 게시하면 양식 입력이 서버로 전송되고 페이지가 새로 고쳐집니다. 데이터는 서버 측에서 처리됩니다. 즉, submit()함수는 실제로 아무것도 반환하지 않고 단지 양식 데이터를 서버로 보냅니다.

당신이 정말로 (페이지 새로 고침없이) 자바 스크립트의 응답을하고 싶다면, 당신은 AJAX를 사용해야합니다, 당신은 AJAX를 사용하는 방법에 대해 이야기를 시작하면, 당신은 것입니다 필요한 라이브러리를 사용할 수 있습니다. jQuery 는 지금까지 가장 인기가 많으며 개인적으로 좋아합니다. jQuery에는 Form 이라는 훌륭한 플러그인이 있습니다.이 플러그인 은 원하는대로 정확하게 작동합니다.

jQuery와 그 플러그인을 사용하는 방법은 다음과 같습니다.

$('#myForm')
    .ajaxForm({
        url : 'myscript.php', // or whatever
        dataType : 'json',
        success : function (response) {
            alert("The server says: " + response);
        }
    })
;

Ajax 대안은 보이지 않는 <iframe>것을 양식의 대상으로 설정 <iframe>하고 onload처리기 에서 해당 내용을 읽습니다 . 그러나 Ajax가있을 때 왜 귀찮게합니까?

참고 : 일부 답변은 Ajax 없이는 불가능하다고 주장하기 때문에이 대안을 언급하고 싶었습니다 .


나는 이런 식으로 일하고 있습니다.

$('#form').submit(function(){
    $.ajax({
      url: $('#form').attr('action'),
      type: 'POST',
      data : $('#form').serialize(),
      success: function(){
        console.log('form submitted.');
      }
    });
    return false;
});

12me21의 의견에서 추출한 비 jQuery 방식 :

var xhr = new XMLHttpRequest();
xhr.open("POST", "/your/url/name.php"); 
xhr.onload = function(event){ 
    alert("Success, server responded with: " + event.target.response); // raw response
}; 
// or onerror, onabort
var formData = new FormData(document.getElementById("myForm")); 
xhr.send(formData);

내용은 POST'기본 콘텐츠 유형은 우리가 위의 코드에서 보내는 것과 일치하는 "응용 프로그램 / x-www-form-urlencoded를"입니다이야. 당신이 "다른 물건"을 보내거나 조정하려면 어떻게 든 여기 에 약간의 중요한 세부 사항을 참조하십시오.


submit ()이 무엇을 이해하는지 잘 모르겠습니다 ...

당신이 할 때 form1.submit();양식 정보는 웹 서버로 전송됩니다.

WebServer는해야 할 모든 작업을 수행하고 새로운 웹 페이지를 클라이언트에 반환합니다 (보통 변경 사항이있는 동일한 페이지).

따라서 form.submit () 액션의 리턴을 "잡을"수있는 방법은 없습니다.


미래 인터넷 검색 자 :

새 브라우저 (2018 년 현재 : Chrome, Firefox, Safari, Opera, Edge 및 대부분의 모바일 브라우저 (IE는 아님)) fetch는 비동기 네트워크 호출을 단순화하는 표준 API입니다 (필요한 경우 XMLHttpRequest또는 jQuery $.ajax).

전통적인 형태는 다음과 같습니다.

<form id="myFormId" action="/api/process/form" method="post">
    <!-- form fields here -->
    <button type="submit">SubmitAction</button>
</form>

위와 같은 양식이 나에게 전달되면 (또는 시맨틱 HTML이므로 양식을 작성한 경우) fetch아래와 같이 이벤트 리스너에서 코드를 랩핑 할 수 있습니다.

document.forms['myFormId'].addEventListener('submit', (event) => {
    event.preventDefault();
    // TODO do something here to show user that form is being submitted
    fetch(event.target.action, {
        method: 'POST',
        body: new URLSearchParams(new FormData(event.target)) // event.target is the form
    }).then((resp) => {
        return resp.json(); // or resp.text() or whatever the server sends
    }).then((body) => {
        // TODO handle body
    }).catch((error) => {
        // TODO handle error
    });
});

(또는 원본 포스터처럼 제출 이벤트없이 수동으로 호출하려는 경우 fetch코드를 넣고을 사용하는 form대신 요소에 대한 참조를 전달하십시오 event.target.)

문서 :

가져 오기 : https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API

기타 : https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Sending_forms_through_JavaScript 2018 년의 페이지에는 페치 (아직)가 언급되어 있지 않습니다. 그러나 target = "myIFrame"트릭은 더 이상 사용되지 않습니다. 또한 'submit'이벤트에 대한 form.addEventListener의 예제도 있습니다.


콜백이 없습니다. 링크를 따르는 것과 같습니다.

서버 응답을 캡처하려면 AJAX를 사용하거나 Iframe에 게시하고 iframe onload()이벤트 후 나타나는 내용을 확인하십시오 .


당신은 할 수 event.preventDefault()귀하의 제출 버튼의 클릭 핸들러에서 HTML 양식의 기본을 보장하기 위하여 submit(페이지 새로 고침에 대한 어떤 단서 인) 이벤트가 발생하지 않습니다.

또 다른 대안은 해커 폼 마크 업을 사용하는 것입니다. 사용 <form>하고 type="submit"있으며 원하는 동작을 방해하고 있습니다. 이로 인해 클릭 이벤트가 페이지를 새로 고치게됩니다.

여전히 사용하려는 경우 <form>, 당신은 사용자 정의 핸들러를 클릭 쓰고 싶지 않아, 당신은 jQuery의 사용 ajax에 대한 약속 방법 노출에 의해 멀리 당신을위한 전체 문제를 추상화 방법을, success, error, 등


요약하면 다음 중 하나를 통해 문제를 해결할 수 있습니다.

• 핸들링 기능을 사용하여 기본 동작 방지 event.preventDefault()

• 요소를 사용하여 (예를 기본 동작을 필요가 없습니다 <form>)

• jQuery 사용 ajax


(방금이 질문이 2008 년에 나온 것으로 나타났습니다. 내 피드에 왜 표시되었는지 확실하지 않습니다. 어쨌든 이것은 분명히 명확한 대답입니다)


    $.ajax({
        url: "/users/login/",    //give your url here
        type: 'POST',
        dataType: "json",
        data: logindata,
        success: function ( data ){
        //  alert(data);    do your stuff
        },
        error: function ( data ){
        //  alert(data);    do your stuff
        }
    });

이것은이 문제에 대한 내 코드입니다.

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

<script type='text/javascript'>
/* 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()} );

  /* Alerts the results */
  posting.done(function( data ) {
    alert('success');
  });
});
</script>

Chrome을 사용하여 AJAX 요청의 출력을 캡처하려는 경우 다음 간단한 단계를 수행 할 수 있습니다.

  1. 프로그래머 도구 상자를 엽니 다
  2. 콘솔로 이동하여 콘솔 내부 어디든지
  3. 나타나는 메뉴에서 "XMXHTTPRequest 로깅 사용"을 클릭하십시오.
  4. 그렇게하면 AJAX 요청을 할 때마다 "XHR finished loading : http : // ......"로 시작하는 메시지가 콘솔에 나타납니다.
  5. 표시되는 링크를 클릭하면 헤더 및 응답 내용을 볼 수있는 "리소스 탭"이 나타납니다.

@rajesh_kw ( https://stackoverflow.com/a/22567796/4946681 ) 의 답변을 바탕으로 양식 게시 오류 및 성공을 처리합니다.

    $('#formName').on('submit', function(event) {
        event.preventDefault(); // or return false, your choice
        $.ajax({
            url: $(this).attr('action'),
            type: 'post',
            data: $(this).serialize(),
            success: function(data, textStatus, jqXHR) {
                // if success, HTML response is expected, so replace current
                if(textStatus === 'success') {
                    // https://stackoverflow.com/a/1236378/4946681
                    var newDoc = document.open('text/html', 'replace');
                    newDoc.write(data);
                    newDoc.close();
                }
            }
        }).fail(function(jqXHR, textStatus, errorThrown) {
            if(jqXHR.status == 0 || jqXHR == 302) {
                alert('Your session has ended due to inactivity after 10 minutes.\nPlease refresh this page, or close this window and log back in to system.');
            } else {
                alert('Unknown error returned while saving' + (typeof errorThrown == 'string' && errorThrown.trim().length > 0 ? ':\n' + errorThrown : ''));
            }
        });
    });

내가 사용하기 this때문에, 내 논리가 재사용 가능한 것을, 나는 그것을 렌더링하고 현재 페이지를 교체 할 수 있도록 HTML의 성공에 반환하고, 세션이 시간 초과되는 경우 내 경우에는 내가 로그인 페이지로 리디렉션을 기대 기대 정도 페이지 상태를 유지하기 위해 리디렉션을 차단합니다.

이제 사용자는 다른 탭을 통해 로그인하고 제출을 다시 시도 할 수 있습니다.


AJAX를 사용해야합니다. 양식을 제출하면 일반적으로 브라우저에 새 페이지가로드됩니다.


당신은 자바 스크립트와 AJAX 기술을 사용하여 그렇게 할 수 있습니다. jquery 와이 양식 플러그 인을 살펴보십시오 . form.submit에 대한 콜백을 등록하려면 두 개의 js 파일 만 포함하면됩니다.


jQueryajax()메소드를 사용하여이를 수행 할 수 있습니다 .

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
function submitform() {
      $.ajax({
        headers: { 
          'Accept': 'application/json',
          'Content-Type': 'application/json' 
        },
        type: "POST",
        url : "/hello.hello",
        dataType : "json",
        data : JSON.stringify({"hello_name": "hello"}),
        error: function () {
          alert('loading Ajax failure');
        },
    	onFailure: function () {
          alert('Ajax Failure');
    	},
    	statusCode: {
          404: function() {
          alert("missing info");
          }   
    	},
        success : function (response) {
          alert("The server says: " + JSON.stringify(response));
        }
      })
      .done(function( data ) {
        $("#result").text(data['hello']);
      });
};</script>


 $(document).ready(function() {
    $('form').submit(function(event) {
        event.preventDefault();
        $.ajax({
            url : "<wiki:action path='/your struts action'/>",//path of url where u want to submit form
            type : "POST",
            data : $(this).serialize(),
            success : function(data) {
                var treeMenuFrame = parent.frames['wikiMenu'];
                if (treeMenuFrame) {
                    treeMenuFrame.location.href = treeMenuFrame.location.href;
                }
                var contentFrame = parent.frames['wikiContent'];
                contentFrame.document.open();
                contentFrame.document.write(data);
                contentFrame.document.close();
            }
        });
    });
});

인용구

처음에는이 사용 ( 'formid'). submit (function (event)) 내에서 $ (document) .ready (function ())을 사용하고 아약스 양식 제출 $ .ajax ({,,, ,}); 매개 변수 u가 요구 사항에 따라 선택할 수 있고 afunction success : function (data) {// 예제를 사용하여 응답 HTML을 div에 넣기를 원하는 모든 것을 수행하십시오}


우선 serializeObject ()가 필요합니다.

$.fn.serializeObject = function () {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function () {
        if (o[this.name]) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

그런 다음 기본 게시물을 작성하고 응답을받습니다.

$.post("/Education/StudentSave", $("#frmNewStudent").serializeObject(), function (data) {
if(data){
//do true 
}
else
{
//do false
}

});

다음 코드는 다중 파트 양식 데이터와 함께 ajax를 사용하여 실행됩니다.

function getUserDetail()
{
    var firstName = document.getElementById("firstName").value;
    var lastName = document.getElementById("lastName").value;
    var username = document.getElementById("username").value;
    var email = document.getElementById("email").value;
    var phoneNumber = document.getElementById("phoneNumber").value;
    var gender =$("#userForm input[type='radio']:checked").val();
    //var gender2 = document.getElementById("gender2").value;
    //alert("fn"+firstName+lastName+username+email);
    var roleIndex = document.getElementById("role");
    var role = roleIndex.options[roleIndex.selectedIndex].value;
    var jobTitleIndex = document.getElementById("jobTitle");
    var jobTitle = jobTitleIndex.options[jobTitleIndex.selectedIndex].value;
    var shiftIdIndex = document.getElementById("shiftId");
    var shiftId = shiftIdIndex.options[shiftIdIndex.selectedIndex].value;


    var addressLine1 = document.getElementById("addressLine1").value;
    var addressLine2 = document.getElementById("addressLine2").value;
    var streetRoad = document.getElementById("streetRoad").value;

    var countryIndex = document.getElementById("country");
    var country = countryIndex.options[countryIndex.selectedIndex].value;

    var stateIndex = document.getElementById("state");
    var state = stateIndex.options[stateIndex.selectedIndex].value;

    var cityIndex = document.getElementById("city");
    var city = cityIndex.options[cityIndex.selectedIndex].value;



    var pincode = document.getElementById("pincode").value;

    var branchIndex = document.getElementById("branch");
    var branch = branchIndex.options[branchIndex.selectedIndex].value;

    var language = document.getElementById("language").value;
    var profilePicture = document.getElementById("profilePicture").value;
    //alert(profilePicture);
    var addDocument = document.getElementById("addDocument").value;


    var shiftIdIndex = document.getElementById("shiftId");
    var shiftId = shiftIdIndex.options[shiftIdIndex.selectedIndex].value;


    var data = new FormData();
    data.append('firstName', firstName);
    data.append('lastName', lastName);
    data.append('username', username);
    data.append('email', email);
    data.append('phoneNumber', phoneNumber);
    data.append('role', role);
    data.append('jobTitle', jobTitle);
    data.append('gender', gender);
    data.append('shiftId', shiftId);
    data.append('lastName', lastName);
    data.append('addressLine1', addressLine1);
    data.append('addressLine2', addressLine2);
    data.append('streetRoad', streetRoad);
    data.append('country', country);
    data.append('state', state);
    data.append('city', city);
    data.append('pincode', pincode);
    data.append('branch', branch);
    data.append('language', language);
    data.append('profilePicture', $('#profilePicture')[0].files[0]);
     for (var i = 0; i < $('#document')[0].files.length; i++) {
            data.append('document[]', $('#document')[0].files[i]);
        }



    $.ajax({
        //url : '${pageContext.request.contextPath}/user/save-user',
        type: "POST",
        Accept: "application/json",
        async: true,
        contentType:false,
        processData: false,
        data: data,
        cache: false,

        success : function(data) {      
            reset();
            $(".alert alert-success alert-div").text("New User Created Successfully!");
         },
       error :function(data, textStatus, xhr){
           $(".alert alert-danger alert-div").text("new User Not Create!");
        }


    });


//

}

jQuery.post ()를 사용 하고 서버에서 잘 구성된 JSON 답변을 반환 할 수 있습니다 . 또한 서버에서 직접 데이터의 유효성을 검사 / 관리 할 수 ​​있습니다. 이는 클라이언트에서 수행하는 것보다 더 안전하고 훨씬 쉬우므로 좋은 방법입니다.

예를 들어 간단한 등록을 위해 사용자 데이터와 함께 html 양식을 서버에 게시해야하는 경우 (fileprofilechanges.php 저장) :

I. 고객 부품 :

HTML 부분 :

<form id="user_profile_form">
  <label for="first_name"><input type="text" name="first_name" id="first_name" required />First name</label>
  <label for="family_name"><input type="text" name="family_name" id="family_name" required />Family name</label>
  <label for="email"><input type="email" name="email" id="email" required />Email</label> 
  <input type="submit" value="Save changes" id="submit" />
</form>

Ib 스크립트 부분 :

$(function () {
    $("#user_profile_form").submit(function(event) {
      event.preventDefault();
      var postData = {
        first_name: $('#first_name').val(),
        family_name: $('#family_name').val(),
        email: $('#email').val()
      };
      $.post("/saveprofilechanges.php", postData,
        function(data) {
          var json = jQuery.parseJSON(data);
          if (json.ExceptionMessage != undefined) {
            alert(json.ExceptionMessage); // the exception from the server
            $('#' + json.Field).focus(); // focus the specific field to fill in
          }
          if (json.SuccessMessage != undefined) {
            alert(json.SuccessMessage); // the success message from server
          }
       });
    });
});

II. 서버 부분 (saveprofilechanges.php) :

$data = $_POST;
if (!empty($data) && is_array($data)) {
    // Some data validation:
    if (empty($data['first_name']) || !preg_match("/^[a-zA-Z]*$/", $data['first_name'])) {
       echo json_encode(array(
         'ExceptionMessage' => "First name missing or incorrect (only letters and spaces allowed).",
         'Field' => 'first_name' // Form field to focus in client form
       ));
       return FALSE;
    }
    if (empty($data['family_name']) || !preg_match("/^[a-zA-Z ]*$/", $data['family_name'])) {
       echo json_encode(array(
         'ExceptionMessage' => "Family name missing or incorrect (only letters and spaces allowed).",
         'Field' => 'family_name' // Form field to focus in client form
       ));
       return FALSE;
    }
    if (empty($data['email']) || !filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
       echo json_encode(array(
         'ExceptionMessage' => "Email missing or incorrectly formatted. Please enter it again.",
         'Field' => 'email' // Form field to focus in client form
       ));
       return FALSE;
    }
    // more actions..
    // more actions..
    try {
       // Some save to database or other action..:
       $this->User->update($data, array('username=?' => $username));
       echo json_encode(array(
         'SuccessMessage' => "Data saved!"
       ));
       return TRUE;
    } catch (Exception $e) {
       echo json_encode(array(
         'ExceptionMessage' => $e->getMessage()
       ));
       return FALSE;
    }
}

아약스없이 할 수 있습니다.

아래와 같이 쓰십시오.

.. .. ..

"action.php"에서

frmLogin.submit () 이후;

변수 $ submit_return.을 읽으십시오.

$ submit_return은 반환 값을 포함합니다.

행운을 빕니다.

참고 URL : https://stackoverflow.com/questions/374644/how-do-i-capture-response-of-form-submit

반응형