javascript - 如何使用原生的XMLHttpRequest对象提交表单?
怪我咯
怪我咯 2017-04-11 12:06:01
[JavaScript讨论组]

HTML:



JavaScript:

var submit = document.getElementById("submit");
        submit.onclick = function() {
            var xhr = new XMLHttpRequest();
            xhr.onreadystatechange = function(){
                if(xhr.state == 4) {
                    if((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) {
                        console.log(xhr.responseText);
                    } else {
                        alert("HttpRequest was unsccessful: " + xhr.status);
                    }
                }
            }
            xhr.open("post", "form.php", true);
            xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
            var form = document.getElementById("info");
            xhr.send(serialize(form));
    }

form.php

代码如上, 我想要达到的效果, 是跟在form里添加了action和method属性一样, 提交后可以自动跳转到form.pp.
但是这样提交并没有反应, 搜了一下, 全是关于jquery的. 还是不知道用ajax提交表单是怎样的格式.

怪我咯
怪我咯

走同样的路,发现不同的人生

全部回复(1)
黄舟
var fd = new FormData;
fd.append("username",document.querySelector("#username").value);
fd.append("password",document.querySelector("#password").value);
...
xhr.send(fd);
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送

Copyright 2014-2026 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号