문제

다음 코드가 있습니다.

<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() 기능은 실제로 아무것도 반환하지 않고 양식 데이터를 서버로 전송합니다.

JavaScript (페이지 새로 고침없이)에서 응답을 원한다면 Ajax를 사용해야하며 Ajax 사용에 대해 이야기하기 시작하면됩니다. 필요 라이브러리를 사용합니다. jQuery 지금까지 가장 인기 있고 개인적으로 좋아하는 것입니다. jQuery 호출에 대한 훌륭한 플러그인이 있습니다 형태 당신이 원하는 것처럼 들리는 것을 정확하게 할 것입니다.

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기본 컨텐츠 유형은 "Application/X-www-form-urlencoded"이며 위의 스 니펫에서 보내는 내용과 일치합니다. "기타 물건"을 보내거나 어떻게 든 조정하려면 여기 약간의 끔찍한 세부 사항.

제출 ()가 무엇을하는지 이해하는지 확실하지 않습니다 ...

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

Webserver는해야 할 일을 수행하고 새로운 웹 페이지를 클라이언트에 반환합니다 (일반적으로 변경된 항목이있는 동일한 페이지).

따라서 Form.Submit () 작업의 반환을 "잡을 수있는"방법이 없습니다.

미래의 인터넷 검색 자 :

새로운 브라우저 (2018 년 기준 : Chrome, Firefox, Safari, Opera, Edge 및 대부분의 모바일 브라우저), IE가 아닌 경우) fetch 비동기 네트워크 호출을 단순화하는 표준 API입니다 (우리가 필요로했던 것 XMLHttpRequest 또는 jQuery 's $.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/learn/html/forms/sending_forms_through_javaScript2018 년의 해당 페이지는 Fetch (아직)를 언급하지 않습니다. 그러나 대상 = "myiframe"트릭이 더 이상 사용되지 않는다고 언급합니다. 또한 '제출'이벤트에 대한 form.addeventListener의 예도 있습니다.

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

서버 응답을 캡처하려면 Ajax를 사용하거나 iframe에 게시하고 iframe의 다음에 나타나는 것을 잡습니다. onload() 이벤트.

당신은 할 수 있습니다 event.preventDefault() 제출 버튼의 클릭 핸들러에서 HTML 양식 기본값이 submit 이벤트는 발사되지 않습니다 (이는 페이지가 새로 고침되는 것입니다).

또 다른 대안은 Hackier Form Markup을 사용하는 것입니다. <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 완료로드 : 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를 사용해야합니다. 양식을 제출하면 일반적으로 브라우저가 새 페이지를로드합니다.

JavaScript 및 Ajax 기술을 사용하여 수행 할 수 있습니다. jQuery와 이것을 살펴보십시오 플러그인 양식. Form.Submit에 대한 콜백을 등록하려면 두 개의 JS 파일 만 포함하면됩니다.

당신은 이것을 사용하여 달성 할 수 있습니다 jQuery 그리고 ajax() 방법:

<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();
            }
        });
    });
});

블록 쿼트

모든 사용 $ (document) .ready (function ())이 사용 ( 'compord'). 제출 (function (event))를 방지 한 다음 ajax 양식 제출 $ .ajax ({,, ,}); 요건에 따라 선택할 수있는 매개 변수 u가 필요합니다. 부위 성공을 호출하십시오 : function (data) {// div}에 응답 html을 넣기 위해 내 예제를 원하는 모든 것을 수행합니다.

우선 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 양식 (SaveProfileChanges.php)에 게시 해야하는 경우 :

I. 클라이언트 부품 :

IA 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;
    }
}

Ajax 없이는 그렇게 할 수 있습니다.

아래와 같이 쓰십시오.

.. .. ..

그리고 "action.php"에서

그런 다음 frmlogin.submit () 후;

variable $ sumb_return을 읽으십시오 ..

$ dopper_return에는 반환 값이 포함되어 있습니다.

행운을 빕니다.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top