Jquery post, response in new window
I have a script that on.DocumentReady posts data to another page. That page responds with some HTML encapsulated in one div tag.
My goal is to have this post response/data open in a new window.
Any hints or clues?
Here is the snippet I created from Dr. Mille's advice.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var packslip_id = 35592;
var po_no = 0018439;
var box_no = 1;
开发者_开发技巧 $.post("https://example.com/barcode/generate", { packing_slip: packslip_id, reference: po_no, total_boxes: box_no},
function (data) {
alert(data);
var win=window.open('about:blank');
with(win.document)
{
open();
write(data);
close();
}
});
});
Use the write()-Method of the Popup's document to put your markup there:
$.post(url, function (data) {
var w = window.open('about:blank');
w.document.open();
w.document.write(data);
w.document.close();
});
Accepted answer doesn't work with "use strict" as the "with" statement throws an error. So instead:
$.post(url, function (data) {
var w = window.open('about:blank', 'windowname');
w.document.write(data);
w.document.close();
});
Also, make sure 'windowname' doesn't have any spaces in it because that will fail in IE :)
If you dont need a feedback about the requested data and also dont need any interactivity between the opener and the popup, you can post a hidden form into the popup:
Example:
<form method="post" target="popup" id="formID" style="display:none" action="https://example.com/barcode/generate" >
<input type="hidden" name="packing_slip" value="35592" />
<input type="hidden" name="reference" value="0018439" />
<input type="hidden" name="total_boxes" value="1" />
</form>
<script type="text/javascript">
window.open('about:blank','popup','width=300,height=200')
document.getElementById('formID').submit();
</script>
Otherwise you could use jsonp. But this works only, if you have access to the other Server, because you have to modify the response.
I did it with an ajax post and then returned using a data url:
$(document).ready(function () {
var exportClick = function () {
$.ajax({
url: "/api/test.php",
type: "POST",
dataType: "text",
data: {
action: "getCSV",
filter: "name = 'smith'",
},
success: function(data) {
var w = window.open('data:text/csv;charset=utf-8,' + encodeURIComponent(data));
w.focus();
},
error: function () {
alert('Problem getting data');
},
});
}
});
精彩评论