Download a file and redirect it to another page via ajax

后端 未结 12 2270
盖世英雄少女心
盖世英雄少女心 2021-02-02 09:44

I have a simple contact form for download excel file . Main issue happen , When ajax load .I want to download excel file then redirect user to a next page.. Below is my code wit

12条回答
  •  遇见更好的自我
    2021-02-02 10:16

    You can achieve this by creating virtual form and post it.

    function autoGenerateAndSubmitForm(method, url, post_data) {
        var element = document.getElementById("virtual_form");
        if(element != null )
        {
            element.parentNode.removeChild(element);
        }
        var form = document.createElement("form");
        form.setAttribute("id", "virtual_form");
        form.setAttribute("style", "display:none;");
        form.setAttribute("target", "_blank"); // This line is very important in your case for redirect in other page and download your file.
        form.method = method;
        form.action = url;   
        for(i in post_data)
        {
             var element=document.createElement("input");
             element.value=post_data[i];
             element.name=i;
             form.appendChild(element); 
        }
        document.body.appendChild(form);
        form.submit();
        form.parentNode.removeChild(form);
    }
    

    Call above method where you need it, i assume uyou have call it in click event

    $('button').on('click', function(e){
         autoGenerateAndSubmitForm("POST","/site/ajaxexcel.php",{'value':'send'});
         location.href = '';     
    });
    

    Remove below line from your server side code.

    header('Content-type: image/jpeg,image/gif,image/png');
    

提交回复
热议问题