PHP提供文件并通过jquery发送消息?
好吧,假设我有以下几页 index.phpPHP提供文件并通过jquery发送消息?,php,jquery,Php,Jquery,好吧,假设我有以下几页 index.php <form action="create_file.php" method="get"> <input type="number" name="num_lines"> <button type="submit">Download File</button> <form> 下载文件 创建_file.php <?php $num_lines = $_GET['
<form action="create_file.php" method="get">
<input type="number" name="num_lines">
<button type="submit">Download File</button>
<form>
下载文件
创建_file.php
<?php
$num_lines = $_GET['num_lines'];
//create a file with $num_lines lines
?>
<?php
$num_lines = $_GET['num_lines'];
die($num_lines);
?>
我怎样才能:
1.)创建一个包含$num_行的文本文件,并将其提供给用户
2.)向用户发送jquery警报,告知下载成功。理想情况下,消息将由create_file.php创建
在使用index.php时,您可以使用ajax。请检查下面的链接,该链接将提醒在create_file.php中消失的文本。。检查一下
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="get">
<input type="number" id="numLines" name="num_lines">
<button id="button" type="button">Download File</button>
<form>
<script>
$(document).on('click','#button',function(){
var val=$('#numLines').val();
$.post('create_file.php',{val:val},function(r){
alert(r)
});
});
</script>
下载文件
$(文档)。在('单击','按钮',函数()上){
var val=$('#numLines').val();
$.post('create_file.php',{val:val},函数(r){
警报(r)
});
});
创建_file.php
<?php
$num_lines = $_GET['num_lines'];
//create a file with $num_lines lines
?>
<?php
$num_lines = $_GET['num_lines'];
die($num_lines);
?>
客户端方法:
或者,您可以做如下操作:
<?php
$num_lines = $_GET['num_lines'];
$ext = '.txt';
$tmpfname = tempnam("./", "numLines_");
if (file_exists($tmpfname)) {
unlink($tmpfname);
file_put_contents($tmpfname . $ext, $num_lines);
echo json_encode(array('fileUrl' => basename($tmpfname) . $ext));
} else {
echo 'err';
}
?>
<!doctype html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(function(){
$.get('create_file.php', {'num_lines': 42}, function(res){
var response = $.parseJSON(res)
if(typeof response =='object') {
var downloadableFileLink = $('<a></a>').attr('href', response.fileUrl).html("Click here to your file, yo.")
$('#downloadTheRapper').append(downloadableFileLink)
console.log('Oh snap.')
} else {
console.log('err')
}
});
});
</script>
</head>
<body>
<div id="downloadTheRapper"></div>
</body>
</html>
$(函数(){
$.get('create_file.php',{'num_line':42},函数(res){
var响应=$.parseJSON(res)
if(响应类型=='object'){
var downloadableFileLink=$('').attr('href',response.fileUrl).html(“单击此处查看您的文件,yo.”)
$('#downloadTheRapper').append(可下载文件链接)
console.log('ohsnap'))
}否则{
console.log('err')
}
});
});
您可以试试这样的方法