How to open a popup with sending POST variable using JavaScript?
How can I open a PHP popup with post data to it?
I have done thi开发者_Python百科s using GET:
<a href='javascript: function(var1);'>click to open</a>
function(var1){
url = "/Test/Popup.php?var="+var1;
params = 'width='+screen.width;
params += ', height='+screen.height;
params += ', top=0, left=0'
params += ', fullscreen=yes';
mapWindow = window.open(url,'myMapWindow', params);
}
I need to do this using POST.
Is there any way?
The window.open()
function doesn't allow for POST
requests. The only alternative would be to use an Ajax call to retrieve the content and then open the popup. You can use jQuery and more specifically jQuery.post()
to load the content and in the callback do this:
$.post('/Test/Popup.php', {'var': var1}, function(data) {
var params = 'width='+screen.width;
params += ', height='+screen.height;
params += ', top=0, left=0'
params += ', fullscreen=yes';
var mapWindow = window.open('', 'myMapWindow', params);
mapWindow.document.write(data);
});
You can't do that via window.open. That will always result in a GET request. It is not possible to get window.open to perform a POST.
You work around it by using an AJAX call to do the post, then have the response handler pop up a window and fill in the response text.
Alternatively, you can dynamically build a form with a method="post"
, and a target="newwindow"
. It won't valiate as proper HTML anymore, but with the target you can force the form's submission response to go into another window.
function GetXmlHttpObject() {
if(window.XMLHttpRequest) {return new XMLHttpRequest();}
if(window.ActiveXObject) {return new ActiveXObject("Microsoft.XMLHTTP");}
return alert ("Your browser does not support ajax! Some features may not be working.. Please upgrade your browser.");
}
var url = "/Test/Popup.php";
var params = "var="+var1;
var http = GetXmlHttpObject();
http.open("POST", url, true);
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
var mapWindow = window.open('', 'myMapWindow', params);
mapWindow.document.write(http.responseText);
}
}
http.send(params);
ajax POST method is a way to send POST requests via javascript combining it with a window can be tricky.. src
you can use mapWindow.document.write(http.responseText);
to add the response text to the window. (credit for window write code goes to @Francois Deschenes)
精彩评论