前端使用formdata非同步上傳form表單,以及後台(php)擷取的詳細教程,親測可用.(附要源碼)

來源:互聯網
上載者:User
這篇文章主要介紹了前端使用formdata非同步上傳form表單,以及後台(php)擷取的詳細教程,親測可用.(附要源碼),有著一定的參考價值,現在分享給大家,有需要的朋友可以參考一下

前端如果要非同步提交一個表單那麼,使用formdata方法提交是不錯的選擇.因為formdata可以將整個表單都提交包括提交表單中的

檔案(這個是重點,很多其他方式不能完成).

前端的關鍵區段代碼如下:

<form id="form"  method="post" enctype="multipart/form-data"><input type="text" name="name" /><input type="file" name=img /><input type="button" onclick="submit()"/></form><script>function submit(){var myform  = document.getElementById("form")var formfile = new FormData(myform);var author = ["sony", "god", "JB"];formfile.append("author",  author);    //此處是在原表單上在增加一些欄位, 後端用$_POST["author"]就可以取得相應的值var xml = new XMLHttpRequest();xml.onreadystatechange =  function(){        if(xml.readyState == 4 &&  xml.status == 200){                var result = JSON.parse(xml.responseText);               console.log(result) //在列印台就可以看到相應的表單值        }}xml.open("POST",  "你要提交到那個伺服器位址", true);xml.send( formfile );}</script>


後台使用php,其他的語言可以參考思路是一樣的 get.php

<?php $name = $_POST["name"];$author = $_POST['author"];$file = $_FILES["img"];move_uploaded_file($file['tmp_name'], $file["name"]);  //上傳到和get.php同一級目錄的伺服器上//至此,前端非同步上傳的name 和author 和 img 都已經取到.後續可以根據自己的需要去做其他事情?>

遇到的坑:

如form.file.append("author", author)可以額外增加自己想要上傳的值,但是author 數值和數組和字串親測可用,但是如果你是想要 增加個表單那是不行如 formfile.append("form", form) 在後台$_POST["form"]得到是 fromElementobject

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.