Displaying php results on current page

半腔热情 提交于 2019-12-13 04:29:20

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!