programing

HTML 양식을 리디렉션 없이 제출하는 방법

minimums 2023. 10. 20. 13:32
반응형

HTML 양식을 리디렉션 없이 제출하는 방법

이런 폼이 있으면.

<form action="/Car/Edit/17" id="myForm" method="post" name="myForm"> ... </form>

자바스크립트/jQuery로 다른 뷰로 리디렉션하지 않고 제출하려면 어떻게 해야 합니까?

스택 오버플로에서 많은 답변을 읽었지만 모두 POST 기능에 의해 반환되는 보기로 리디렉션됩니다.

양식의 방향을 변경하여 이를 달성할 수 있습니다.action보이지 않는 곳까지<iframe>. 자바스크립트나 다른 종류의 스크립트를 필요로 하지 않습니다.

<iframe name="dummyframe" id="dummyframe" style="display: none;"></iframe>

<form action="submitscript.php" target="dummyframe">
    <!-- Form body here -->
</form>

원하는 것을 달성하려면 아래와 같이 jQuery Ajax를 사용해야 합니다.

$('#myForm').submit(function(e){
    e.preventDefault();
    $.ajax({
        url: '/Car/Edit/17/',
        type: 'post',
        data:$('#myForm').serialize(),
        success:function(){
            // Whatever you want to do after the form is successfully submitted
        }
    });
});

이것도 시도해 보십시오.

function SubForm(e){
    e.preventDefault();
    var url = $(this).closest('form').attr('action'),
    data = $(this).closest('form').serialize();
    $.ajax({
        url: url,
        type: 'post',
        data: data,
        success: function(){
           // Whatever you want to do after the form is successfully submitted
       }
   });
}

최종해

이것은 완벽하게 작동했습니다.이 기능을 호출합니다.Html.ActionLink(...)

function SubForm (){
    $.ajax({
        url: '/Person/Edit/@Model.Id/',
        type: 'post',
        data: $('#myForm').serialize(),
        success: function(){
            alert("worked");
        }
    });
}

현재 모든 답변은 iframe으로 jQuery나 트릭을 사용하기 때문에, 단순한 자바스크립트만으로 메소드를 추가하는 것은 아무런 해가 없다고 판단했습니다.

function formSubmit(event) {
  var url = "/post/url/here";
  var request = new XMLHttpRequest();
  request.open('POST', url, true);
  request.onload = function() { // request successful
  // we can use server response to our request now
    console.log(request.responseText);
  };

  request.onerror = function() {
    // request failed
  };

  request.send(new FormData(event.target)); // create FormData from form that triggered event
  event.preventDefault();
}

// and you can attach form submit event like this for example
function attachFormSubmitEvent(formId){
  document.getElementById(formId).addEventListener("submit", formSubmit);
}

숨김을 놓습니다.iFrame당신의 페이지 하단에 그리고target당신의 형태로:

<iframe name="hiddenFrame" width="0" height="0" border="0" style="display: none;"></iframe>

<form action="/Car/Edit/17" id="myForm" method="post" name="myForm" target="hiddenFrame"> ... </form>

빠르고 쉽게.기억해두시구요.target속성은 여전히 광범위하게 지원되며 HTML 4.01에서 더 이상 사용되지 않습니다.

그래서 미래를 대비하기 위해 정말로 Ajax를 사용해야 합니다.

좋아요, 마법같은 방법을 알려주지는 않겠습니다.양식 요소에 대해 설정된 수행 특성이 있으면 리디렉션됩니다.

리디렉션하지 않으려면 아무 작업도 설정하지 않고 설정하기만 하면 됩니다.onsubmit="someFunction();"

당신의someFunction()(AJAX와 함께든 아니든) 당신이 원하는 것은 무엇이든 하고, 마지막에는 당신이 덧붙입니다.return false;브라우저에 양식을 제출하지 말라고 하는 것...

데이터를 다음과 같이 전송하지 않는 경우 2020년 현재의 원-라이너 솔루션multipart/form-data아니면application/x-www-form-urlencoded:

<form onsubmit='return false'>
    <!-- ... -->           
</form>

아약스가 있어야 가능합니다.이와 같은 것:

$(document).ready(function(){
    $("#myform").on('submit', function(){
        var name = $("#name").val();
        var email = $("#email").val();
        var password = $("#password").val();
        var contact = $("#contact").val();

        var dataString = 'name1=' + name + '&email1=' + email + '&password1=' + password + '&contact1=' + contact;
        if(name=='' || email=='' || password=='' || contact=='')
        {
            alert("Please fill in all fields");
        }
        else
        {
            // Ajax code to submit form.
            $.ajax({
                type: "POST",
                url: "ajaxsubmit.php",
                data: dataString,
                cache: false,
                success: function(result){
                    alert(result);
                }
           });
        }
        return false;
    });
});

jQuery's 보기post기능.

버튼을 만들고 그 버튼을 설정합니다.onClickListener($('#button').on('click', function(){});), 그리고 함수에 있는 데이터를 보냅니다.

참고:preventDefault기능, jQuery!

여기에 설명된 대로 제출 버튼을 양식 외부로 이동하여 원하는 효과를 얻을 수도 있습니다.

페이지 재로드 방지 및 양식 제출 ajax/jquery에서 리디렉션

다음과 같은 경우:

<form id="getPatientsForm">
    Enter URL for patient server
    <br/><br/>
    <input name="forwardToUrl" type="hidden" value="/WEB-INF/jsp/patient/patientList.jsp" />
    <input name="patientRootUrl" size="100"></input>
    <br/><br/>
</form>

<button onclick="javascript:postGetPatientsForm();">Connect to Server</button>

이 토막글을 사용하면 양식을 제출하고 리디렉션을 피할 수 있습니다.대신 성공 함수를 인수로 넘겨 원하는 대로 할 수 있습니다.

function submitForm(form, successFn){
    if (form.getAttribute("id") != '' || form.getAttribute("id") != null){
        var id = form.getAttribute("id");
    } else {
        console.log("Form id attribute was not set; the form cannot be serialized");
    }

    $.ajax({
        type: form.method,
        url: form.action,
        data: $(id).serializeArray(),
        dataType: "json",
        success: successFn,
        //error: errorFn(data)
    });
}

그 다음엔 그냥 해요.

var formElement = document.getElementById("yourForm");
submitForm(formElement, function() {
    console.log("Form submitted");
});

바닐라 js + svelte를 불태우고 잊어버립니다.

function handleSubmit(e) {
    const request = new Request(`/products/${item.ItemCode}?_method=PUT`, { 
        method: 'POST', 
        body: new FormData(e.target),
    });
    fetch(request)
}

스벨테에서 사용:

<form method="post" on:submit|preventDefault={handleSubmit}>

웹 구성요소를 사용하면 이를 잘 처리하는 쉽게 재사용 가능한 양식 구성요소를 만들 수 있습니다.

function urlencodeFormData(fd: FormData) {
  let s = '';
  function encode(s: string) {
    return encodeURIComponent(s).replace(/%20/g, '+');
  }
  const formData: [string, string][] = [];
  fd.forEach((value, key) => {
    if (value instanceof File) {
      formData.push([key, value.name]);
    } else {
      formData.push([key, value]);
    }
  });
  for (const [key, value] of formData) {
    s += (s ? '&' : '') + encode(key) + '=' + encode(value);
  }
  return s;
}

const xhrOnSubmit = (event: SubmitEvent) => {
  console.log('Form submitted');
  const form: HTMLFormElement | null =
    event.target instanceof HTMLFormElement ? event.target : null;
  if (form == null) {
    console.error('Event target of form listener is not a form!');
    return;
  }
  let baseUrl = form.action;
  if (baseUrl == null || baseUrl === '') {
    baseUrl = window.location.href;
  }

  const requestUrl = new URL(baseUrl, window.location.href);
  
const shouldClear = form.getAttribute('data-clear-form') === 'true';

  // Decide on encoding
  const formenctype =
    event.submitter?.getAttribute('formenctype') ??
    event.submitter?.getAttribute('formencoding');
  const enctype =
    formenctype ??
    form.getAttribute('enctype') ??
    form.getAttribute('encoding') ??
    'application/x-www-form-urlencoded';

  // Decide on method
  let formMethod =
    event.submitter?.getAttribute('formmethod') ??
    form.getAttribute('method')?.toLowerCase() ??
    'get';

  const formData = new FormData(form);

  // Encode body
  let body: BodyInit | null = null;
  if (formMethod === 'get') {
    requestUrl.search = new URLSearchParams(
      urlencodeFormData(formData)
    ).toString();
  } else if (formMethod === 'post') {
    if (enctype === 'application/x-www-form-urlencoded') {
      body = urlencodeFormData(formData);
    } else if (enctype === 'multipart/form-data') {
      body = formData;
    } else if (enctype === 'text/plain') {
      let text = '';
      // @ts-ignore - FormData.entries() is not in the TS definition
      for (const element of formData.keys()) {
        text += `${element}=${JSON.stringify(formData.get(element))}\n`;
      }
    } else {
      throw new Error(`Illegal enctype: ${enctype}`);
    }
  } else if (formMethod === 'dialog') {
    // Allow default behavior
    return;
  } else {
    throw new Error(`Illegal form method: ${formMethod}`);
  }

  // Send request
  const requestOptions: RequestInit = {
    method: formMethod,
    headers: {
      'Content-Type': enctype,
    },
  };
  if (body != null && formMethod === 'post') {
    requestOptions.body = body;
  }
  const response = fetch(baseUrl, requestOptions).then((response) => {
    if (shouldClear) {
      form.reset();
    }
    if (response.ok) {
      form.dispatchEvent(
        new CustomEvent('xhr-form-success', {
          detail: response,
        })
      );
    } else {
      form.dispatchEvent(
        new CustomEvent('xhr-form-failure', {
          detail: response,
        })
      );
    }
    return response;
  });

  event.preventDefault();
};

customElements.define(
  'xhr-form',
  class extends HTMLFormElement {
    constructor() {
      console.log('Form constructed');
      super();
    }

    connectedCallback() {
      this.addEventListener('submit', xhrOnSubmit);
    }

    disconnectedCallback() {
      this.removeEventListener('submit', xhrOnSubmit);
    }
  },
  { extends: 'form' }
);

사용 예(이벤트와 관련된 모든 작업은 선택 사항):

<form action="/printer" method="post" id="xhr-form" is="xhr-form">
  <h2>XHR POST Test</h2>
  <input type="text" name="name" placeholder="Name">
  <input type="number" name="age" placeholder="Age">
  <input type="submit" value="Submit">
</form>

<script>
  const xhrForm = document.getElementById('xhr-form');

  xhrForm.addEventListener('xhr-form-success', (event) => {
    console.log('XHR Form Success', event.detail);
  });

  xhrForm.addEventListener('xhr-form-failure', (event) => {
    console.log('XHR Form Failure', event.detail);
  });
</script>

뒷단을 조절하면 다음과 같은 것을 사용합니다.response.redirect대신에response.send.

사용자 정의 HTML 페이지를 만들거나 이미 가지고 있는 것으로 리디렉션할 수 있습니다.

Express.js:

const handler = (req, res) => {
  const { body } = req
  handleResponse(body)
  .then(data => {
    console.log(data)
    res.redirect('https://yoursite.com/ok.html')
  })
  .catch(err => {
    console.log(err)
    res.redirect('https://yoursite.com/err.html')
  })
}
...
app.post('/endpoint', handler)

언급URL : https://stackoverflow.com/questions/25983603/how-to-submit-an-html-form-without-redirection

반응형