简体   繁体   中英

Ajax to post a form and download file in response

The following javascript is used to submit a webform to be processed and in return either an error is returned or a file is return on success. the script below is posting the form successfully however how can i get change the script to both download the file or show the response.

note that i am receiving the file, but is it not getting downloaded, the file contents are showing on the console.log

Code:

    $("#myform").submit(function(event) {

        /* stop form from submitting normally */
        event.preventDefault();

        /* get some values from elements on the page: */
        var $form = $(this),
            term = "tesr",
            url = $form.attr('action');

        var data = $('#myform').serialize();
        /* Send the data using post */
        //var posting = $.post(url, data, function(response) { console.log("1"); });

        $.ajax({
            type: "post",
            url: url,
            data: data,
            contentType: "application/x-www-form-urlencoded",
            success: function(responseData, textStatus, jqXHR) {
                alert("data saved")
            },
            error: function(jqXHR, textStatus, errorThrown) {
            console.log(jqXHR); 
console.log(errorThrown);
            }
        })


    });

    <form name="myform" id="myform" onsubmit="return validateForm()" method="post" action="/audit_submit"> 
    <input type="submit" id="generate-string"  value="Ok">
    <div id="result">test</div>

*UPDATE:

It seems that the Ajax is receiving the file in the error function

this is a print out of console.log(jqXHR);

{readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}

here is a print out of responsedata 在此处输入图片说明

If your response is an byte array, you can use the code mentioned below.

var bytes = new Unit8Array(responseData)
var blob = new Blob([bytes],{type:"application/vnd.openxmlformats-officedocument.wordprocessingml.document"})
var link= document.createElement('a')
link.href= window.URL.createObjectURL(blob)
link.download="filename.docx"
link.click()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM