首页 > 代码库 > AJAX-----13HTML5中新增的API---FormData

AJAX-----13HTML5中新增的API---FormData

FormData 表单数据对象,这是在HTML5中新增的一个API,他能以表单对象做参数,自动的将表单的数据打包,当ajax发送数据是,发送FormData内的表单数据给后端即可

 

技术分享

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<script>
    function fd(){
        var fdate = document.getElementById(fdate);
        var fd = new FormData(fdate);
        var xhr = new XMLHttpRequest();
        xhr.open(post,10.php,true);
        xhr.send(fd);
        xhr.onreadystatechange = function(){
            if(this.readyState == 4){
                document.getElementById(desc).innerHTML = this.responseText;
            }
        }
        
    }
</script>
<body>
    <form id="fdate" >
        user:<input type="text" name="user"> <br><br>
        age:<input type="text" name="age"> <br><br>
        sex:<input type="text" name="sex"> <br><br>
        QQ:<input type="text" name="QQ"> <br><br>
        <input type="button" value="Go" onclick="fd();"> 
    </form>
    <p id="desc"></p>
</body>
</html>

 

 

技术分享

 

效果如下所示:

技术分享

 

这样比传统的拼接方法简单多了,当然他还有另外一种用法,如下所示:

 

技术分享

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
</head>
<script>
    function fd(){
        var fdate = document.getElementById(fdate);
        var fd = new FormData(fdate);
        var fd2 = new FormData();
        var xhr = new XMLHttpRequest();
        xhr.open(post,10.php,true);
        //xhr.send(fd);
        fd2.append(user,leigood);
        fd2.append(age,18);
        xhr.send(fd2);
        xhr.onreadystatechange = function(){
            if(this.readyState == 4){
                document.getElementById(desc).innerHTML = this.responseText;
            }
        }
        
    }
</script>
<body>
    <form id="fdate" >
        user:<input type="text" name="user"> <br><br>
        age:<input type="text" name="age"> <br><br>
        sex:<input type="text" name="sex"> <br><br>
        QQ:<input type="text" name="QQ"> <br><br>
        <input type="button" value="Go" onclick="fd();"> 
    </form>
    <p id="desc"></p>
</body>
</html>

 

效果如下所示:

技术分享

 

AJAX-----13HTML5中新增的API---FormData