jQuery serialize in javascript


jQuery serialize in javascript

我想知道javascript中是否有一些东西可以做与.serialize()相同的工作。我需要用someform.onsubmit = funct...<form onsubmit="...。我只需要得到所有的数据在这种形式(就像jQuery一样)作为一个字符串。

提前感谢

我认为最接近的是使用FormData。比如:

document.querySelector('form').addEventListener('submit', function (e) {
    e.preventDefault();
    xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function () {
        if (xhr.readyState == 4 && xhr.status == 200) {
            console.log(xhr.responseText);
        }
    }
    xhr.open("POST", "/echo/json");
    xhr.send(new FormData(this));
});

可以说,这比在表单集合上调用.serialize更简单,但请注意,您显然无法检查FormData对象内部的内容。这也是相对较新的,所以不是很跨浏览器兼容