To transition in an HTML/JS page is easy. window.navigate and you're there.
Passing parameters : no problem, just put the query string in the URL.
However, when the parameters you want to pass get a bit BIG (>2000 chars approx), the query string gets chopped....
No problem, we just use a POST and pass the parameters in the body as multipart/form-data, don't we?
But in html dom, no way to do this cleanly in JS. Sure, ajax allows to send data to a URL as a post, but we don't transition the page...
Seems like to only way is to auto-generate a <form> in the html page, fill it in with the parameters as <input> fields, and submit it ourselves...
Heres the code I ended up with, and specifically the first method which is very useful when your URL already has the massive query string lined up and ready to go (so you want to parse it into input fields, rather than having it as a nice separate params map).
Note that the first method is based on code I found on Chris West's blog, except that his regex replaces didn't work for me so I had to adapt them.
// Post to the given URL, extracting its params to be POST body params
function postUrl(url) {
var form = document.createElement("FORM");
form.method = "POST";
form.enctype = "multipart/form-data";
form.style.display = "none";
// extract the query string part (and replace with ""), and it gets passed to the
// first closure function (e1 is the whole match, urlArgs is the match without the ?
form.action = url.replace(/\?(.*)/, function(e1, urlArgs) {
// Now decompose the query string into each key=value pair, and treat each one found
// Again, the closure function gets e2 as the full match string, key,value as the submatches
urlArgs.replace(/([^&=]+)=([^&=]*)/g, function(e2, key, value) {
// By creating a new INPUT element in the form.
var input = document.createElement("INPUT");
input.type = "hidden";
input.name = decodeURIComponent(key);
input.value = decodeURIComponent(value);
form.appendChild(input);
return "";
});
return "";
});
document.body.appendChild(form);
form.submit();
}
// Post to the given URL (which should have NO params), passing the given params
function postUrlWithParams(path, params) {
// The rest of this code assumes you are not using a library.
// It can be made less wordy if you use one.
var form = document.createElement("form");
form.setAttribute("method", "POST");
form.setAttribute("action", path);
form.setAttribute("enctype", "multipart/form-data");
// Note that this doesn't deal with a param which is an array... an exercise for the reader if required
for(var key in params) {
if(params.hasOwnProperty(key)) {
var hiddenField = document.createElement("input");
hiddenField.setAttribute("type", "hidden");
hiddenField.setAttribute("name", key);
hiddenField.setAttribute("value", params[key]);
form.appendChild(hiddenField);
}
}
document.body.appendChild(form);
form.submit();
}
Enjoy...
mardi 4 juin 2013
Inscription à :
Articles (Atom)