2013-01-17 66 views
0

我有一個形式的HTML中這樣說:Ajax表單數據序列化失敗

<html> 

<head> 
    <script type="text/javascript" src="js/jquery-1.8.3.js"></script> 
</head> 

<body> 
    <form action="accept-file.php" method="post" enctype="multipart/form-data" id="theform"> 
    Your Photo: <input id="thefile" type="file" name="photo" size="25" /> 
    <input type="button" name="submit" value="Submit" onclick="submitform();"/> 
    </form> 
</body> 

<script> 

    function submitform() 
    { 
    data = $('*').serialize(); 

    $.post(
     'http://localhost/banksoal/1.0.0/accept-file.php', 
     data 
    ); 
    } 

</script> 

</html> 

和.php爲這樣的腳本:

 <?php 
    //if they DID upload a file... 
    if($_FILES['photo']['name']) 
    { 
    print_r($_FILES['photo']); 
    $message = 'default message'; 

    //if no errors... 
    if(!$_FILES['photo']['error']) 
    { 
     //now is the time to modify the future file name and validate the file 
     $new_file_name = 'd:\\' . '--test-- '.basename($_FILES['photo']['name']); //rename file 
     if($_FILES['photo']['size'] > (1024000)) //can't be larger than 1 MB 
     { 
     $valid_file = false; 
     $message = 'Oops! Your file\'s size is to large.'; 
     } 
     else 
     { 
     $valid_file = true; 
     } 

     //if the file has passed the test 
     if($valid_file) 
     { 
     //move it to where we want it to be 
     move_uploaded_file($_FILES['photo']['tmp_name'], $new_file_name); 
     $message = 'Congratulations! Your file was accepted.'; 
     } 
    } 
    //if there is an error... 
    else 
    { 
     //set that to be the returned message 
     $message = 'Ooops! Your upload triggered the following error: '.$_FILES['photo']['error']; 
    } 
    } 

    var_dump($message); 
?> 

問題: 在submitform( )函數,在腳本標記處在該行:

data = $('*').serialize(); 

爲什麼我得到空結果? 代碼有什麼問題?

謝謝

+0

你試過上載準備腳本使用ajax的文件? – Gntem

+0

@GeoPhoenix,我還沒有嘗試上傳文件的腳本(比如這個:http://blueimp.github.com/jQuery-File-Upload/)。 請幫助我,我不明白這一點:如果文件在用戶提交表單之前到達服務器,我怎麼能關聯哪些文件屬於哪個表單提交。 – fasisi

回答

0

您不能上傳使用Ajax的文件,如果你必須以類似AJAX的方式上傳文件,你可以使用hidd設置目標屬性等於iframe並獲取iframe的內容以知道請求是否失敗

這就是我通常爲此目的而創建的隱藏iframe,它將成爲目標形式,這樣的事情:

<iframe name='formTarget' src='#' style='display:none;' onload='processResult(this);'></iframe> 

和processResult您可以獲取通過iframe的內容:

$(results).html(); 

當iframe中加載這樣,它會自動觸發功能,告知請求完成

1

改變這種

data = $('*').serialize(); 

data = $('theform').serialize(); 

和改變這種

<form action="accept-file.php" method="post" enctype="multipart/form-data" id="theform"> 

<form action="accept-file.php" method="post" enctype="multipart/form-data" id="theform" name ="theform"> 
+0

'#形式',而不是'形式'。 – AgentFire