簡體   English   中英

上傳文件和ajax / jquery失敗

[英]Upload file and ajax/jquery fails

我正在嘗試將文件上傳功能添加到聯系表單,但是由於某些原因它無法正常工作。 上載腳本本身可以正常工作,但是當我將其添加到聯系代碼時,jQuery腳本使其失敗。

如您所知,我絕不是專家。

pontact.php

    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
    <script type="text/javascript">
    $(function(){
        $('#contact_form').submit(function(e){
            e.preventDefault();
            var form = $(this);
            var post_url = form.attr('action');
            var post_data = form.serialize();
            $('#loader', form).html('<img src="loader.gif" /> Please Wait...');
            $.ajax({
                type: 'POST',
                url: post_url, 
                data: post_data,
                success: function(msg) {
                    $(form).fadeOut(500, function(){
                        form.html(msg).fadeIn();
                    });
                }
            });
        });
    });
    </script>
    </head>
    <body>
    <form action="process.php" method="post" id="contact_form">
        <div>
             <label for="name">Your Name:</label>
             <input type="text" name="name" id="name" value="" tabindex="1" />
        </div>
        <div>
             <label for="email">Your Email:</label>
             <input type="text" name="email" id="email" value="" tabindex="2" />
        </div>
        <div>
            <label for="message">Message:</label>
            <textarea cols="40" rows="8" name="message" id="message"></textarea>
        </div>
<div>
    <input type="hidden" name="MAX_FILE_SIZE" value="512000" />
    Send this file: <input name="userfile" type="file" />
</div>
        <div id="loader">
            <input type="submit" value="Submit" /> 
        </div>
    </form>
    </body>
    </html>

Process.php

$uploaddir = '/var/www/download/';
$uploadfile = $uploaddir . basename($_FILES['userfile']['name']);

echo "<p>";

if (move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadfile)) {
  echo "File is valid, and was successfully uploaded.\n";
} else {
   echo "Upload failed";
}

echo "</p>";
echo '<pre>';
echo 'Here is some more debugging info:';
print_r($_FILES);
print "</pre>";

即使您調用form.serialize()文件上傳也form.serialize()通過jQuery進行。

您可以通過黑客攻擊(例如使用iFrames(此處的好文章 ))或基於Flash的上傳器(例如Uploadify )來達到相同的效果。

默認情況下,您無法使用ajax 上傳文件 (( 為什么我不能異步上傳文件?

但是有一些技術,包括您可以使用的iframe或Flash插件

希望這可以幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM