在jquery ajax中使用e.preventDefault()时图像未发布 [英] Image isn't posting while using e.preventDefault() in jquery ajax

查看:79
本文介绍了在jquery ajax中使用e.preventDefault()时图像未发布的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用jquery ajax发布表单时遇到一些有线问题.我有多个图像上传字段.当我使用e.preventDefault()函数时,图像未上传.但是,当我禁用此代码.它仍然很好.这是我的标记,js和php的代码段

HTML

<form class="shoform" id="contact-entry" name="contact-entry" action="project-up-eng.php" method="post" enctype="multipart/form-data">
<input class="pic" id="img" type="file" multiple="multiple" name="imgfile[]" />
<input class="submitbtn" id="submitbtn" type="submit" value="Add"></input>
</form>

JS

$("#submitbtn").click(function(){


        $("#contact-entry").submit(function() {
        /* Act on the event */

        e.preventDefault();
        $.post('project-up-eng.php',$(this).serialize(), function()
                        {
                        alert("OK");


                    });

    }); 

});

PHP:

mkdir("projects/".$_POST['name']);
$path="projects/".$_POST['name'];
for($i=0;$i<count($_FILES['imgfile']['size']);$i++)
{
$file = $path."/".$_FILES['imgfile']['name'][$i];
move_uploaded_file($_FILES['imgfile']['tmp_name'][$i],$file);   

}

解决方案

不幸的是,您无法使用经典HTML通过AJAX提交包含文件的表单. 当您呼叫e.preventDefault()时,不会执行常规文件上传,而您手动呼叫的$.post只是无法做您想做的事.

您可以在具有新HTML 5功能的新浏览器中使用JavaScript上传.请参阅"如何使用AJAX上传文件". /p>

I got some wired problem while posting a form using jquery ajax. i have a multiple image upload field. while i use e.preventDefault() function the images aren't uploading. but while i disable this code. it remains fine. here is my code snippet for markup, js and php

HTML

<form class="shoform" id="contact-entry" name="contact-entry" action="project-up-eng.php" method="post" enctype="multipart/form-data">
<input class="pic" id="img" type="file" multiple="multiple" name="imgfile[]" />
<input class="submitbtn" id="submitbtn" type="submit" value="Add"></input>
</form>

JS

$("#submitbtn").click(function(){


        $("#contact-entry").submit(function() {
        /* Act on the event */

        e.preventDefault();
        $.post('project-up-eng.php',$(this).serialize(), function()
                        {
                        alert("OK");


                    });

    }); 

});

PHP:

mkdir("projects/".$_POST['name']);
$path="projects/".$_POST['name'];
for($i=0;$i<count($_FILES['imgfile']['size']);$i++)
{
$file = $path."/".$_FILES['imgfile']['name'][$i];
move_uploaded_file($_FILES['imgfile']['tmp_name'][$i],$file);   

}

解决方案

Unfortunately, you can not submit forms with files over AJAX with classic HTML. When you call e.preventDefault(), the regular file upload is not performed, and your $.post you call manually is just unable to do what you want.

You can upload with JavaScript in new browsers with new HTML 5 functionality. See "How can I upload files with AJAX".

这篇关于在jquery ajax中使用e.preventDefault()时图像未发布的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆