programing

jQuery Ajax 함수의 전체 양식을 데이터로 전달합니다.

cafebook 2023. 2. 27. 22:22
반응형

jQuery Ajax 함수의 전체 양식을 데이터로 전달합니다.

저는 jQuery ajax 함수를 가지고 있으며, 전체 양식을 포스트 데이터로 제출하고 싶습니다.폼을 계속 갱신하고 있기 때문에 요청으로 전송해야 할 폼 입력을 계속 갱신하는 것은 귀찮습니다.

정확히 다음과 같은 기능을 수행하는 기능이 있습니다.

http://api.jquery.com/serialize/

var data = $('form').serialize();
$.post('url', data);

serialize()는 post 메서드를 사용하여 폼을 보내는 경우 권장되지 않습니다.예를 들어, Ajax를 통해 파일을 전달하려는 경우 작동하지 않습니다.

ID가 "myform"인 폼이 있다고 가정합니다.

보다 나은 솔루션은 FormData를 만들어 전송하는 것입니다.

    let myform = document.getElementById("myform");
    let fd = new FormData(myform );
    $.ajax({
        url: "example.php",
        data: fd,
        cache: false,
        processData: false,
        contentType: false,
        type: 'POST',
        success: function (response) {
            // do something with the result
        }
    });

일반 사용serialize()폼 요소 위에 있습니다.

복수의 <select>옵션은 같은 키로 시리얼화 됩니다.예를 들어 다음과 같습니다.

<select id="foo" name="foo" multiple="multiple">
    <option value="1">one</option>
    <option value="2">two</option>
    <option value="3">three</option>
</select>

는 동일한 쿼리 파라미터의 여러 발생을 포함하는 쿼리 문자열을 생성합니다.

[path]?foo=1&foo=2&foo=3&someotherparams...

백엔드에서 원하는 것이 아닐 수 있습니다.

이 JS 코드를 사용하여 여러 파라미터를 콤마로 구분된 단일 키(John Resig의 위치에 있는 스레드 상의 코멘트 응답에서 부끄럽지 않게 복사)로 줄입니다.

function compress(data) {
    data = data.replace(/([^&=]+=)([^&]*)(.*?)&\1([^&]*)/g, "$1$2,$4$3");
    return /([^&=]+=).*?&\1/.test(data) ? compress(data) : data;
}

위의 내용을 다음과 같이 변환합니다.

[path]?foo=1,2,3&someotherparams...

JS 코드에서는 다음과 같이 부릅니다.

var inputs = compress($("#your-form").serialize());

도움이 됐으면 좋겠다.

사용하다

시리얼라이즈()

var str = $("form").serialize();

Ajax 요청으로 서버로 전송될 수 있는 쿼리 문자열에 폼을 직렬화합니다.

이를 위한 적절한 jQuery 옵션은 FormData를 사용하는 것입니다.이 방법은 폼을 통해 파일을 전송할 때도 적합합니다.

<form id='test' method='post' enctype='multipart/form-data'>
   <input type='text' name='testinput' id='testinput'>
   <button type='submit'>submit</button>
</form>

jQuery의 송신 함수는 다음과 같습니다.

$( 'form#test' ).submit( function(){
   var data = new FormData( $( 'form#test' )[ 0 ] );

   $.ajax( {
      processData: false,
      contentType: false,

      data: data,
      dataType: 'json',
      type: $( this ).attr( 'method' );
      url: 'yourapi.php',
      success: function( feedback ){
         console.log( "the feedback from your API: " + feedback );
      }
});

양식에 데이터를 추가하려면 양식에서 숨겨진 입력을 사용하거나 즉시 추가할 수 있습니다.

var data = new FormData( $( 'form#test' )[ 0 ] );
data.append( 'command', 'value_for_command' );

jquery ajax 함수 집합 매개 변수를 사용하여 데이터를 게시하기만 하면 됩니다.여기 예가 있습니다.

<script>
        $(function () {

            $('form').on('submit', function (e) {

                e.preventDefault();

                $.ajax({
                    type: 'post',
                    url: 'your_complete url',
                    data: $('form').serialize(),
                    success: function (response) {
                        //$('form')[0].reset();
                       // $("#feedback").text(response);
                        if(response=="True") {
                            $('form')[0].reset();
                            $("#feedback").text("Your information has been stored.");
                        }
                        else
                            $("#feedback").text(" Some Error has occured Errror !!! ID duplicate");
                    }
                });

            });

        });
    </script>

다른 솔루션은 나에게 효과가 없었다.현재 작업 중인 프로젝트의 이전 DOSCTYPE가 HTML5 옵션을 허용하지 않을 수도 있습니다.

솔루션:

<form id="form_1" action="result.php" method="post"
 onsubmit="sendForm(this.id);return false">
    <input type="hidden" name="something" value="1">
</form>

js:

function sendForm(form_id){
    var form = $('#'+form_id);
    $.ajax({
        type: 'POST',
        url: $(form).attr('action'),
        data: $(form).serialize(),
        success: function(result) {
            console.log(result)
        }
    });
}

언급URL : https://stackoverflow.com/questions/2019608/pass-entire-form-as-data-in-jquery-ajax-function

반응형