XMLHttpRequest POST multipart/form-data

后端 未结 7 1594
清酒与你
清酒与你 2020-12-04 20:33

I want to use XMLHttpRequest in JavaScript to POST a form that includes a file type input element so that I can avoid page refresh and get useful XML back.

I can sub

7条回答
  •  情书的邮戳
    2020-12-04 20:55

    Here is an up to date way using FormData (full doc @MDN)

    Script:

    var form = document.querySelector('#myForm');
    form.addEventListener("submit", function(e) {
        var xhr = new XMLHttpRequest();
        xhr.open("POST", this.action);
        xhr.addEventListener("load", function(e) {
            // Your callback
        });
    
        xhr.send(new FormData(this));
    
        e.preventDefault();
    });
    

    (from this basic form)

    ...

    Thanks again to Alex Polo for his answer

提交回复
热议问题