dpvp56187 2015-04-10 05:01
浏览 65
已采纳

使用JQuery ajax从多个HTML表单发送数据

Hello I just starting learning jquery ajax to upload file.

I'm using simple html form here and embedding javascript/jquery code in it to perform ajax request.

<!DOCTYPE HTML>

<html>
<head>
    <script type='text/javascript' src='jquery-2.1.3.min.js'></script>
</head>
<body>
    <form id='entryform' method="">
        <input id='formText' type='text' name='text'><br>
        <input id='formFile' type='file' name='file'>
    </form>
    <div id='fill'></div>
</body>
<script>
    $(document).ready(function(){
        $('#entryform').change(function(e){
            e.preventDefault();
            $.ajax({
                url : 'ajax.php',
                data : new FormData(this),
                processData : false,
                contentType : false,
                type : 'POST',
                success : function (retval){
                    $('#fill').html(retval);
                } 
            });
        });
    });
</script>

And this is the PHP code for process :

<?php 

$updir = 'images/';

move_uploaded_file($_FILES['file']['tmp_name'], $updir.$_FILES['file']['name']);

//echo $updir._FILES['file']['name'];
echo "<img src='".$updir.$_FILES['file']['name']."'>";

I the above code i'm trying to upload an image without reloading the page and show the image to the immadiately after the image has been uploaded.

But when i'm trying to run the code, I'm getting a weird behaviour, that is when entering the input to text form the value from the text form that was newly entered is showing immediately.

I mean I want the form file is showed immediately to the user when uploading done not the form text.

Any idea how to fix this? without omitting the text form ?

  • 写回答

1条回答 默认 最新

  • dongyuluan7494 2015-04-10 06:13
    关注

    I guess you need to add the Event handler to formFile so this will help you.

    $(document).ready(function () {
        $('#formFile').change(function (e) {
            var myfiles = $(this).get(0);
            var files = myfiles.files;
            var data = new FormData();
            for (i = 0; i < files.length; i++) {
                data.append('file', files[i]);
            }
            e.preventDefault();
            $.ajax({
                url : 'ajax.php',
                data : data,
                processData : false,
                contentType : false,
                type : 'POST',
                success : function (retval) {
                    $('#fill').html(retval);
                }
            });
        });
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 三种调度算法报错 有实例
  • ¥15 关于#python#的问题,请各位专家解答!
  • ¥200 询问:python实现大地主题正反算的程序设计,有偿
  • ¥15 smptlib使用465端口发送邮件失败
  • ¥200 总是报错,能帮助用python实现程序实现高斯正反算吗?有偿
  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥20 java在应用程序里获取不到扬声器设备