将数据从php返回到html

时间:2017-05-21 09:03:10

标签: php jquery html ajax forms

我是php和html的新手,我有一个问题。我有form上传文件:

    <h2>Upload file</h2>                
    <form name="uploadFile" action = "upload.php" method = "POST" enctype = "multipart/form-data">
    <input type = "file" name = "document"/>
    <input type = "submit"/>

在我的外部upload.php文件中,如果上传成功,我会回显一个包含文件名和消息的字符串。如果我使用echo函数显示值,则值是正确的,但我不想重定向到upload.php页面,我想以HTML格式显示它。

如何在HTML表单页面中打印upload.php文件的返回值?

4 个答案:

答案 0 :(得分:1)

请更改您的index.php文件,如下所示:

<?php
      if(isset($_FILES['document'])) {
        echo $_FILES["document"]["name"];
        echo "<p id='results'></p>";
?>
<script>
        $(document).ready(function() {
            $.ajax({
                url: "data.json",
                dataType: "text",
                success: function(data) {
                    $('#results').html(data);
               }
           });
        });
</script>

<?php } ?>
<h2>Upload file</h2>                
<form name="uploadFile" method = "POST" enctype = "multipart/form-data">
    <input type = "file" name = "document"/>
    <input type = "submit"/>
</form>

这将打印您上传的文件的文件名 使用文件上传时,PHP会将名称文件大小以及所有其他属性保存到$_FILES变量,这是一个全局变量。

正如您所说,您希望在文件上传后立即阅读其他文件,这可能有所帮助。

答案 1 :(得分:0)

您可以使用GET变量重定向到php页面:upload.php?status=success 然后,您可以检查status变量

答案 2 :(得分:0)

添加您的PHP代码,以便在您的表单所在文件的顶部上传,并将其命名为.PHP文件。请尝试以下代码,

<?php
  if(isset($_POST['document'])) {
    //do your post actions here
    //validate your input
    //upload the file
    //print success or error message
  }
?>
<h2>Upload file</h2>                
<form name="uploadFile" method = "POST" enctype = "multipart/form-data">
  <input type = "file" name = "document"/>
  <input type = "submit"/>

答案 3 :(得分:-1)

Nirav发布了答案。使用它进行一些修改。

<?php
if(isset($_FILES['document'])) {
    echo $_FILES["document"]["name"];
    // when uploaded the file assign status=1;
    $file_name=$_FILES["document"]["name"];
    $status="1";
}
?>
<script type="text/javascript">
var status = <?php echo $status; ?>;
var filename = <?php echo $file_name; ?>;
$(document).ready(function(){
    if(status){
        $.ajax({
        url: "upload.php",
        type: "POST",
        data: {
            status:status,
            filename: filename
        }
        success: function(result){
                    $('#element').html(result);
                }
        });
    }
    else{
        $('#element').html("failed"); 
    }

});
</script>

<强> HTML

<h2>Upload file</h2>                
<form name="uploadFile" action="upload.php" method = "POST" enctype = "multipart/form-data">
  <input type = "file" name = "document"/>
  <input type = "submit"/>
</form>
<div id="element"><!--Here Show message from upload.php--></div>

<强> upload.php的

<?php
if(isset($_POST['status']) && !empty($_POST['status'])){

    echo $_POST['filename']." uploaded successfully";
}
?>