问题
I have this coding that allows me show the .txt file contents of whatever file is selected from the drop down.
<form name="add" method="post" id="add" action="show.php">
Choose a file:
<select name="files" id="files" onchange="this.form.submit()">
<option value="File1">File1</option>
<option value="File2">File2</option>
</select>
</form>
with corresponding show.php (yes the purpose was to display only the last three lines of the file):
<?php
$ChosenFile = $_POST['files'];
$file = $ChosenFile.'.txt';
$contents = escapeshellarg($file);
$line = `tail -n 3 $contents`;
echo nl2br($line);
echo "<br><br>";
?>
Trying to get it to display the results below the select drop down instead of direct to the php itself with this code:
<script>
$('#files').on('change', function(){
$.get('show.php', function(data);
$('#result').html(data);
});
});
</script>
<div id="result"></div>
The php works and displays text contents but I can't get it to display below the drop down. What did I miss?
回答1:
remove onchanged
attribute form select
tag
Choose a file:
<select name="files" id="files">
<option value="File1">File1</option>
<option value="File2">File2</option>
</select>
you must send form data to show.php
file to get correct result back
<script>
$(function(){
$('#files').on('change', function(){
$.ajax({
url: 'show.php',
type: 'post',
data: $('form#add').serialize()
}).done(function(data) {
$('#result').html(data);
});
});
});
</script>
回答2:
As your original html and php uses POST
, you would need to use POST
in your ajax script as well.
And you are not sending any data to your script.
So the result should be something like:
$('#files').on('change', function(){
$.post('show.php', $(this).closest('form').serialize(), function(data);
$('#result').html(data);
});
});
As mentioned in the comments, you also only need one event handler.
来源:https://stackoverflow.com/questions/22309844/displaying-php-results-on-current-page