javascript - 通过正文中的 fetch() 发送 GET 数据,而不是在 URL 中指定它
问题描述
我正在尝试使用 MDN(https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Supplying_request_options)中提到的 fetch() 将此 jQuery 调用转换为本机 Javascript。
$.ajax(
{
method: "GET",
url: CB_ABS_URI + "ajax/get-checkin.php",
dataType: "json",
data: { DwellingUnitID:DwellingUnitID },
})
至
// Example POST method implementation:
async function postData(url = '', data = {}) {
// Default options are marked with *
const response = await fetch(url, {
method: 'GET', // *GET, POST, PUT, DELETE, etc.
mode: 'cors', // no-cors, *cors, same-origin
cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached
credentials: 'same-origin', // include, *same-origin, omit
headers: {
'Content-Type': 'application/json'
// 'Content-Type': 'application/x-www-form-urlencoded',
},
redirect: 'follow', // manual, *follow, error
referrerPolicy: 'no-referrer', // no-referrer, *client
body: JSON.stringify(data) // body data type must match "Content-Type" header
});
return await response.json(); // parses JSON response into native JavaScript objects
}
postData(CB_ABS_URI + "ajax/get-checkin.php", { DwellingUnitID: DwellingUnitID })
.then((data) => {
console.log(data); // JSON data parsed by `response.json()` call
});
但我似乎无法在正文中发送 GET 数据。将查询添加到 ajax/get-checkin.php 是唯一的方法吗?
解决方案
但我似乎无法在正文中发送 GET 数据
fetch
明确区分 URL 中的查询字符串和请求正文中的数据(不像 jQuery,它根据请求方法在它们之间切换)。
将查询添加到 ajax/get-checkin.php 是唯一的方法吗?
是的,请参阅文档:
如果要使用 URL 查询参数:
var url = new URL("https://geo.example.org/api"), params = {lat:35.696233, long:139.570431} Object.keys(params).forEach(key => url.searchParams.append(key, params[key])) fetch(url).then(/* … */)
推荐阅读
- sql-server - 拒绝对存储过程中的表的选择权限 - SQL Server
- arrays - MIPS将字符放入字符串中的位置正在删除字符串的堆地址
- javascript - 似乎无法通过 JavaScript 表单传递变量
- apache-spark - PySpark:反序列化包含在 eventthub 捕获 avro 文件中的 Avro 序列化消息
- c# - 将 Json Graph 转换为单类对象
- python - 将数据从 CSV 导入张量流,无效参数错误
- java - 当我只选择 ID 时,ObjectDB 返回 Integer 而不是 Long,但仅适用于某些实体
- jquery - 使用 jquery 和 ajax 提交表单
- excel - 如何让 Powerapps 自动生成现有的 Excel 下拉列表?
- json - 使用Rails解析JSon后将图片URL转为图片