如何使用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
和HEAD
方法:
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; }