How to replace window.open(…) with a POST

后端 未结 2 1859
渐次进展
渐次进展 2020-12-02 07:05

I currently have some code that runs a window.open(urlWithGetParams) line. As far as I\'m aware, this is going to force me to use a GET request. I

相关标签:
2条回答
  • 2020-12-02 07:43

    In fact I made a small "library" for this, open in POST a new window :

    // Arguments :
    //  verb : 'GET'|'POST'
    //  target : an optional opening target (a name, or "_blank"), defaults to "_self"
    window.io = {
        open: function(verb, url, data, target){
            var form = document.createElement("form");
            form.action = url;
            form.method = verb;
            form.target = target || "_self";
            if (data) {
                for (var key in data) {
                    var input = document.createElement("textarea");
                    input.name = key;
                    input.value = typeof data[key] === "object"
                        ? JSON.stringify(data[key])
                        : data[key];
                    form.appendChild(input);
                }
            }
            form.style.display = 'none';
            document.body.appendChild(form);
            form.submit();
            document.body.removeChild(form);
        }
    };
    

    Example :

    io.open('POST', 'fileServer.jsp', {request: {key:"42", cols:[2, 3, 34]}});
    

    To open in a new window, set the target parameter :

    io.open('POST', someURL, someArgs, 'newwin');
    

    or to ensure it's a new window/tab each time :

    io.open('POST', someURL, someArgs, '_blank');
    
    0 讨论(0)
  • 2020-12-02 07:53

    What I do is that I do a javascript AJAX post and then I take the content that I get back and place it into a new window.

    Something like this (using jQuery, but you can use any AJAX implementation):

    $.post(URL, DATA, function(d){
        var new_window = window.open();
        $(new_window.document.body).append(d);
    });
    
    0 讨论(0)
提交回复
热议问题