Отправка данных GET через fetch () в теле вместо указания их в URL - PullRequest
0 голосов
/ 31 марта 2020

Я пытаюсь преобразовать этот jQuery вызов в нативный Javascript, используя fetch (), как указано в MDN (https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Supplying_request_options).

        $.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 единственным способом?

1 Ответ

0 голосов
/ 31 марта 2020

Но я не могу отправить данные 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(/* … */)
...