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?

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

Другие решения

Клиентский подход:
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>
0

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector