source

jQuery에서 Ajax-requests와 함께 FormData 개체를 전송하려면 어떻게 해야 합니까?

goodcode 2023. 1. 9. 21:37
반응형

jQuery에서 Ajax-requests와 함께 FormData 개체를 전송하려면 어떻게 해야 합니까?

XMLHttpRequest Level 2 표준(아직 작업 중인 초안)에서는FormData인터페이스입니다.이 인터페이스를 사용하면,File오브젝트로부터 XHR-Requests(Ajax-requests)로 이행합니다.

덧붙여서, 이것은 신기능입니다.과거에는, 「숨겨진 iframe 트릭」이 사용되고 있었습니다(다른 질문으로 확인).

동작은 다음과 같습니다(예).

var xhr = new XMLHttpRequest(),
    fd = new FormData();

fd.append( 'file', input.files[0] );
xhr.open( 'POST', 'http://example.com/script.php', true );
xhr.onreadystatechange = handler;
xhr.send( fd );

어디에input는 입니다.<input type="file">필드 및handler는 Ajax-request 성공 핸들러입니다.

이것은, 모든 브라우저(IE 제외)에서 올바르게 동작합니다.

이제 이 기능을 jQuery에서 사용할 수 있도록 하겠습니다.이거 해봤어요.

var fd = new FormData();    
fd.append( 'file', input.files[0] );

$.post( 'http://example.com/script.php', fd, handler );

안타깝게도 이 기능은 작동하지 않습니다('불법 호출' 오류가 발생함 - 스크린샷이 여기에 있음).jQuery는 폼필드 이름/값을 나타내는 단순한 키 값 개체를 기대하고 있습니다.FormData제가 지나치는 케이스는 양립할 수 없는 것 같아요

자, 이제 합격이 가능하기 때문에FormData에 인스턴스하다.xhr.send()jQuery에서도 동작할 수 있으면 좋겠습니다.


업데이트:

jQuery's Bug Tracker에서 "기능 티켓"을 만들었습니다.여기 http://bugs.jquery.com/ticket/9995에서 확인하실 수 있습니다.

'아작스 프리필터'를 쓰라는 제안을 받았는데...


업데이트:

먼저 제가 어떤 행동을 하고 싶은지 데모를 해보겠습니다.

HTML:

<form>
    <input type="file" id="file" name="file">
    <input type="submit">
</form>

JavaScript:

$( 'form' ).submit(function ( e ) {
    var data, xhr;

    data = new FormData();
    data.append( 'file', $( '#file' )[0].files[0] );

    xhr = new XMLHttpRequest();

    xhr.open( 'POST', 'http://hacheck.tel.fer.hr/xml.pl', true );
    xhr.onreadystatechange = function ( response ) {};
    xhr.send( data );

    e.preventDefault();
});

위의 코드에 의해, 다음의 HTTP 요구가 발생합니다.

다중 형식 데이터

필요한 것은 이것입니다.멀티파트/폼데이터 콘텐츠 타입을 원합니다.


제안하는 솔루션은 다음과 같습니다.

$( 'form' ).submit(function ( e ) {
    var data;

    data = new FormData();
    data.append( 'file', $( '#file' )[0].files[0] );

    $.ajax({
        url: 'http://hacheck.tel.fer.hr/xml.pl',
        data: data,
        processData: false,
        type: 'POST',
        success: function ( data ) {
            alert( data );
        }
    });

    e.preventDefault();
});

단, 그 결과 다음과 같은 결과가 됩니다.

잘못된 내용 유형

보시다시피 콘텐츠 유형이 잘못되었습니다...

이렇게 할 수 있을 것 같아요.

var fd = new FormData();    
fd.append( 'file', input.files[0] );

$.ajax({
  url: 'http://example.com/script.php',
  data: fd,
  processData: false,
  contentType: false,
  type: 'POST',
  success: function(data){
    alert(data);
  }
});

주의:

  • 설정processData로.falsejQuery가 데이터를 쿼리 문자열로 자동 변환하지 않도록 할 수 있습니다.상세한 것에 대하여는, 문서를 참조해 주세요.

  • 의 설정contentType로.false필수입니다.그렇지 않으면 jQuery가 잘못 설정되기 때문입니다.

아직 언급해야 할 몇 가지 기술이 있습니다.내용 설정부터 시작합니다.Ajax 매개 변수에 속성을 입력합니다.

Pradeek의 예를 바탕으로:

$('form').submit(function (e) {
    var data;

    data = new FormData();
    data.append('file', $('#file')[0].files[0]);

    $.ajax({
        url: 'http://hacheck.tel.fer.hr/xml.pl',
        data: data,
        processData: false,
        type: 'POST',

        // This will override the content type header, 
        // regardless of whether content is actually sent.
        // Defaults to 'application/x-www-form-urlencoded'
        contentType: 'multipart/form-data', 

        //Before 1.5.1 you had to do this:
        beforeSend: function (x) {
            if (x && x.overrideMimeType) {
                x.overrideMimeType("multipart/form-data");
            }
        },
        // Now you should be able to do this:
        mimeType: 'multipart/form-data',    //Property added in 1.5.1

        success: function (data) {
            alert(data);
        }
    });

    e.preventDefault();
});

치 않은을 하도록 jQuery ajax는 과 같습니다.beforeSend이벤트는 그것을 하기에 좋은 장소입니다.한동안 사람들은 그것을 사용하고 있었다.beforeSend5.1.5.1추가되기 덮어쓰다.할 수 .before send 에서는 jqXHR을 송신하기 전에 jqXHR을 변경할 수 .

다음 코드를 사용하여 Ajax 요청으로 FormData 개체를 전송할 수 있습니다.

$("form#formElement").submit(function(){
    var formData = new FormData($(this)[0]);
});

이는 수용된 답변과 매우 유사하지만 질문 주제에 대한 실제 답변입니다.이렇게 하면 FormData에 폼 요소가 자동으로 전송되므로 데이터를 FormData 변수에 수동으로 추가할 필요가 없습니다.

아약스법은 이렇게 생겼는데

$("form#formElement").submit(function(){
    var formData = new FormData($(this)[0]);
    //append some non-form data also
    formData.append('other_data',$("#someInputData").val());
    $.ajax({
        type: "POST",
        url: postDataUrl,
        data: formData,
        processData: false,
        contentType: false,
        dataType: "json",
        success: function(data, textStatus, jqXHR) {
           //process data
        },
        error: function(data, textStatus, jqXHR) {
           //process error msg
        },
});

또한 FormData 개체 내의 폼 요소를 다음과 같은 매개 변수로 수동으로 전달할 수도 있습니다.

var formElem = $("#formId");
var formdata = new FormData(formElem[0]);

도움이 됐으면 좋겠다.;)

저는 이렇게 하고 있습니다.제게 도움이 됐으면 좋겠어요:)

   <div id="data">
        <form>
            <input type="file" name="userfile" id="userfile" size="20" />
            <br /><br />
            <input type="button" id="upload" value="upload" />
        </form>
    </div>
  <script>
        $(document).ready(function(){
                $('#upload').click(function(){

                    console.log('upload button clicked!')
                    var fd = new FormData();    
                    fd.append( 'userfile', $('#userfile')[0].files[0]);

                    $.ajax({
                      url: 'upload/do_upload',
                      data: fd,
                      processData: false,
                      contentType: false,
                      type: 'POST',
                      success: function(data){
                        console.log('upload success!')
                        $('#data').empty();
                        $('#data').append(data);

                      }
                    });
                });
        });
    </script>   

JavaScript:

function submitForm() {
    var data1 = new FormData($('input[name^="file"]'));
    $.each($('input[name^="file"]')[0].files, function(i, file) {
        data1.append(i, file);
    });

    $.ajax({
        url: "<?php echo base_url() ?>employee/dashboard2/test2",
        type: "POST",
        data: data1,
        enctype: 'multipart/form-data',
        processData: false, // tell jQuery not to process the data
        contentType: false // tell jQuery not to set contentType
    }).done(function(data) {
        console.log("PHP Output:");
        console.log(data);
    });
    return false;
}

PHP:

public function upload_file() {
    foreach($_FILES as $key) {
        $name = time().$key['name'];
        $path = 'upload/'.$name;
        @move_uploaded_file($key['tmp_name'], $path);
    }
}

$.ajax를 할 수 .beforeSendevent를 입니다.

beforeSend: function(xhr) { 
    xhr.setRequestHeader('Content-Type', 'multipart/form-data');
}

상세한 것에 대하여는, 다음의 링크를 참조해 주세요.http://msdn.microsoft.com/en-us/library/ms536752(v=vs.85).aspx

ajax를 사용하여 파일을 제출하려면 "jquery.form.js"를 사용합니다.이것에 의해, 모든 폼 요소가 간단하게 송신됩니다.

샘플 http://jquery.malsup.com/form/ #ajax Submit

개략도:

<form id='AddPhotoForm' method='post' action='../photo/admin_save_photo.php' enctype='multipart/form-data'>


<script type="text/javascript">
function showResponseAfterAddPhoto(responseText, statusText)
{ 
    information= responseText;
    callAjaxtolist();
    $("#AddPhotoForm").resetForm();
    $("#photo_msg").html('<div class="album_msg">Photo uploaded Successfully...</div>');        
};

$(document).ready(function(){
    $('.add_new_photo_div').live('click',function(){
            var options = {success:showResponseAfterAddPhoto};  
            $("#AddPhotoForm").ajaxSubmit(options);
        });
});
</script>

- 아, 아, 아,fd.append( 'userfile', $('#userfile')[0].files[0]);

- 용 - -fd.append( 'file', $('#userfile')[0].files[0]);

언급URL : https://stackoverflow.com/questions/6974684/how-to-send-formdata-objects-with-ajax-requests-in-jquery

반응형