Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
486 views
in Technique[技术] by (71.8m points)

java - How to download file via Ajax with HTTP POST (i.e. some info in body)?

Download popup dialog can be displayed by

window.location = "someUrl"

or just simply have a link that send HTTP GET method and so on. I've done this successfully.

But now I want to do Ajax with HTTP POST. The POST body has JSON like

{"val1":"key1", "val2":"key2"}

Then in servlet side, it read the JSON and execute query against DB to get data then generate Excel based on the query data.

The part I can't get it working is client side.

Assugming that my servlet at resources/report/schedule generates Excel file.

This does not popup download dialog when using Ajax :( Can anybody help me how to have download dialog with Ajax?

  function post25() {
            var jsonInput = {};
            jsonInput['作業区コード'] = "481";
            jsonInput['機械コード'] = "11";
            jsonInput['作業日'] = "2000/01/01";
            jsonInput = JSON.stringify(jsonInput);

            var ajaxRequest = new XMLHttpRequest();
            ajaxRequest.onreadystatechange = function() {
                if(ajaxRequest.readyState == 4 && ajaxRequest.status == 200) {
                    var res = ajaxRequest.responseText;
                    //location.href = "../resources/report/schedule";
                }
                else if(ajaxRequest.status == 409 || ajaxRequest.status == 500 || ajaxRequest.status == 204) {
                    alert(ajaxRequest.status);
                    document.getElementById("showMessage").innerHTML = ajaxRequest.responseText;
                }
            }
            ajaxRequest.open("POST", "../resources/report/schedule", true);
            ajaxRequest.setRequestHeader("Content-Type", "application/json");
            ajaxRequest.send(jsonInput); 
        }//end post25()
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For security reason it is not allowed to download file using ajax.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...