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);
                }
            });
        });
    });
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大
  • ¥15 import arcpy出现importing _arcgisscripting 找不到相关程序