1. One of the two files is the browser page, and the other is the background php file. I want to use the php header to download the document. After writing as follows, how can I pop up a dialog box prompting for download on the browser page? Currently, there is no response when clicking download in the browser window, but if you directly click the download.php file in the document list window, the download window will pop up. The desired effect is that clicking download directly on the browser interface will pop up the download dialog box
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>PHP download file</title>
<style type="text/css">
</style>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(e){
$("#download").click(function(){
// alert();
$.ajax({
type:"POST",
url:"download.php",
});
});
});
</script>
</head>
<body>
<h2>Download Center</h2>
<p id="download" style="cursor: pointer;">Download</p>
</body>
</html>
Backend php file:
<?php
$file = "C:\file.txt";
$fileName = basename($file); //Get the file name
header("Content-Type:application/octet-stream");
header("Content-Disposition:attachment;filename=".$fileName);
header("Accept-ranges:bytes");
header("Accept-Length:".filesize($file));
$h = fopen($file, 'r');//Open the file
echo fread($h, filesize($file)); //Read the file and output the file (i.e. download the file)
?>
< /p>
You should use windows.location.href="/download.php" behind the pop-up window or directly jump to the a tag behind the pop-up window
ajax sends and receives data in the background, you will only return the data to js.