PHP提供文件并通过jquery发送消息?

时间:2017-01-19 07:10:37

标签: php jquery

好的说我有以下页面。

的index.php

<form action="create_file.php" method="get">
    <input type="number" name="num_lines">
    <button type="submit">Download File</button>
<form>

create_file.php

<?php
     $num_lines = $_GET['num_lines'];
     //create a file with $num_lines lines
?>

我怎么能够:

1。)使用$ num_lines行创建一个文本文件并将其提供给用户

2.。)向用户发送jquery警报,说明下载成功。理想情况下,消息将由create_file.php。

创建

所有留在index.php?

2 个答案:

答案 0 :(得分:1)

你可以使用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>

create_file.php

<?php
     $num_lines = $_GET['num_lines'];
    die($num_lines);
?>

答案 1 :(得分:0)

客户端方法: http://jsfiddle.net/uselesscode/qm5ag/

或者,您可以执行以下操作:

<?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>