0

我有一个 ajaxForm jQuery 库来完成任务,创建了一个示例脚本,如下所示:

HTML & JS

<!doctype html>
<body>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<style>
form { display: block; margin: 20px auto; background: #eee; border-radius: 10px; padding: 15px }
#progress { position:relative; width:400px; border: 1px solid #ddd; padding: 1px; border-radius: 3px; }
#bar { background-color: #B4F5B4; width:0%; height:20px; border-radius: 3px; }
#percent { position:absolute; display:inline-block; top:3px; left:48%; }
</style>
</head>
<body>
<h1>Ajax File Upload Demo</h1>

<form id="myForm" action="" method="post" enctype="multipart/form-data">
     <input type="file" size="60" name="myfile" id="myfile">
     <input type="submit" value="Ajax File Upload">
 </form>

 <div id="progress">
        <div id="bar"></div>
        <div id="percent">0%</div >
</div>
<br/>

<div id="message"></div>

<script>
$(document).ready(function()
{


 $('#myfile').change(function(){

    var options = {
url: "doajaxfileupload.php",
    beforeSend: function()
    {
        $("#progress").show();
        //clear everything
        $("#bar").width('0%');
        $("#message").html("");
        $("#percent").html("0%");
    },
    uploadProgress: function(event, position, total, percentComplete)
    {
        $("#bar").width(percentComplete+'%');
        $("#percent").html(percentComplete+'%');

    },
    success: function()
    {
        $("#bar").width('100%');
        $("#percent").html('100%');

    },
    complete: function(response)
    {
        $("#message").html("<font color='green'>"+response.responseText+"</font>");
    },
    error: function()
    {
        $("#message").html("<font color='red'> ERROR: unable to upload files</font>");

    }

};

     $("#myForm").ajaxForm(options);

});
});

</script>
</body>

</html>

否 在这里,当使用“提交”按钮提交表单时,此脚本可以正常工作。

但我尝试在单击/更改文件上传按钮时上传文件,无需单击提交按钮即可立即上传文件,但没有成功。

当然它不起作用,因为$('#myForm').ajaxForm(options);表单提交的过程。

现在可以在这个脚本中做什么来满足我的要求。请指导。

4

1 回答 1

2

I changed $("#myForm").ajaxForm(options); to:

$("#myForm").ajaxSubmit(options);

See the working JS Fiddle Demo.

Reason for this change:
You need to use ajaxSubmit so you can manage the events in your options. ajaxForm does not allow you to bind the events because it is 'managed'.

Use ajaxSubmit if you want to bind your own submit handler to the form.

Use ajaxForm when you want the plugin to manage all the event binding for you.

(Source: Comments in the Ajax Form JQuery Plugin)


This is using the Ajax Forms jQuery Plugin. Your HTML has two links to jQuery, should one of them not be to the jQuery forms plugin?

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.io/jquery.form.js"></script>
于 2013-07-25T09:11:21.110 回答