12

如何使用fetchapi javascript ( https://github.com/github/fetch ) 传递查询字符串?

var url = "http://www.abcd.com";
var query = {
    a: "test",
    b: 2
};

http://www.abcd.com?a=test&b=2当我将一些参数传递给时,上面应该转换为fetch

4

1 回答 1

7
var params = Object.keys(query)
                   .map((key) => encodeURIComponent(key) + "=" + encodeURIComponent(query[key]))
                   .join("&")
                   .replace(/%20/g, "+");

fetch(url + "?" + params);

或与options对象 -但这不适用于GETandHEAD方法

fetch(url, {
    method: "POST",
    body: convertObjectToFormData(query)
}).then(...);

function convertObjectToFormData(obj) {
    var formData = new FormData();
    for (var key in obj) {
        formData.append(key, obj[key]);
    }
    return formData;
}
于 2016-01-09T11:09:45.130 回答