如何使用fetch
api 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
如何使用fetch
api 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
var params = Object.keys(query)
.map((key) => encodeURIComponent(key) + "=" + encodeURIComponent(query[key]))
.join("&")
.replace(/%20/g, "+");
fetch(url + "?" + params);
或与options
对象 -但这不适用于GET
andHEAD
方法:
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;
}