将FormData转换为查询字符串的更简单方法 [英] Easier way to transform FormData into query string

查看:823
本文介绍了将FormData转换为查询字符串的更简单方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过XMLHttpRequest发送POST请求,并将数据输入到HTML表单中.不受JavaScript干扰的表单将提交其编码为application/x-www-form-urlencoded的数据.

I’m sending a POST request via XMLHttpRequest with data entered into an HTML form. The form without interference of JavaScript would submit its data encoded as application/x-www-form-urlencoded.

使用XMLHttpRequest,我想通过FormData API发送数据,该API无法正常工作,因为它会将数据视为已编码为multipart/form-data.因此,我需要将数据作为查询字符串(正确转义)写入XMLHttpRequest的send方法.

With the XMLHttpRequest, I wanted to send the data with via the FormData API which does not work since it treats the data as if it were encoded as multipart/form-data. Therefor I need to write the data as a query string, properly escaped, into the send method of the XMLHttpRequest.

addEntryForm.addEventListener('submit', function(event) {
    // Gather form data
    var formData = new FormData(this);
    // Array to store the stringified and encoded key-value-pairs.
    var parameters = []
    for (var pair of formData.entries()) {
        parameters.push(
            encodeURIComponent(pair[0]) + '=' +
            encodeURIComponent(pair[1])
        );
    }

    var httpRequest = new XMLHttpRequest();
    httpRequest.open(form.method, form.action);

    httpRequest.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

    httpRequest.onreadystatechange = function() {
        if (httpRequest.readyState === XMLHttpRequest.DONE) {
            if (httpRequest.status === 200) {
                console.log('Successfully submitted the request');
            } else {
                console.log('Error while submitting the request');
            }
        }
    };

    httpRequest.send(parameters.join('&'));

    // Prevent submitting the form via regular request
    event.preventDefault();
});

现在,整个带有for ... of循环的内容,等等,似乎有些令人费解.有没有更简单的方法可以将FormData转换为查询字符串?还是可以以某种方式发送具有不同编码的FormData?

Now this whole thing with the for ... of loop, etc. seems a bit convoluted. Is there a simpler way to transform FormData into a query string? Or can I somehow send FormData with a different encoding?

推荐答案

您可以使用 URLSearchParams

const queryString = new URLSearchParams(new FormData(myForm)).toString()

这篇关于将FormData转换为查询字符串的更简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆