首页 > 解决方案 > 通过正文中的 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 是唯一的方法吗?

标签: javascriptajaxfetch

解决方案


但我似乎无法在正文中发送 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(/* … */)

推荐阅读