ajax上傳文件,提交表單,使用FormData和XMLHttpRequest提交表單

<!DOCTYPE html>
<html>
<head>
    <title>Html5 Ajax 上傳文件</title>
</head>
<body>

<form id="myform">

<input type="text" name="name" value="123" />
<input type="text" name="pwd" value="321" />

<input type="file" id="file" name="myfile" />

<input type="button" onclick="SubmitForm()" value="提交" />

</form>
</body>
<script>
    function SubmitForm() 
    {
        //FormDat對象
        var formobj = new FormData();

        //獲取表單中的數據
        var name = document.getElementsByTagName('name').value;
        var pwd = document.getElementsByTagName('pwd').value;
        var myfile = document.getElementById('file').files[0];

        //向對象中添加要發送的數據
        formobj.append('name',name);
        formobj.append('pwd',pwd);
        formobj.append('myfile',myfile);

        //XMLHttpRequest對象
        var xmlobj = new XMLHttpRequest();

        //指定提交類型和選擇要發送的地址
        xmlobj.open('post','./test.php');

        //發送數據
        xmlobj.send(formobj);

        xmlobj.onload = function()
        {
            alert(xmlobj.responseText);//獲取後臺返回的數據
        }
    }

</script>
</html>
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51

又或者可以更加簡便的

    function SubmitForm() 
    {
        //實例化FormDat對象時傳入form表單對象
        var formobj = new FormData(document.getElementById('myform'));

        //XMLHttpRequest對象
        var xmlobj = new XMLHttpRequest();

        //指定提交類型和選擇要發送的地址
        xmlobj.open('post','./test.php');

        //發送數據
        xmlobj.send(formobj);

        xmlobj.onload = function()
        {
            alert(xmlobj.responseText);//獲取後臺返回的數據
        }
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

PHP代碼:

<?php

$aa = $_FILES['myfile'];//接收文件
$bb = $_POST;//接收數據
move_uploaded_file($aa['tmp_name'],'./123.jpg');//上傳文件

echo 1;//返回數據
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章