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
190 views
in Technique[技术] by (71.8m points)

javascript - How to replace window.open(...) with a POST

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 would like to do this with a POST request. Is there a workaround for this?

I'm not married to window.open(), either. I'm open to just about any alternative that allows me to spawn a new window via a POST request instead of a GET.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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');

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

...