Home > Blockchain >  Convert jquery ajax to fetch
Convert jquery ajax to fetch

Time:07-06

Does someone knows jquery and can help me convert this ajax to js fetch ? Unfortunately, I don't know jquery and I need to convert this into js fetch.

function ajaxLogoutDetailsApi() {
  $.ajax({
    type: "GET",
    url: "OIDCGetLogoutDetails",
    async: false,
    cache: false,
    data: "json",
    success: function (data, status, xhr) {
      data = data.replace('\/\*', '');
      data = data.replace('\*\/', '');
      var dataJson = JSON.parse(data);
      if (dataJson.logoutUrl != null) {
        document.location.href = dataJson.logoutUrl;
      }
    },
    error: function (xhr, status, err) {
      console.log("error in ajaxLogoutDetailsApi");
    }
  });
}

Appreciate every hint.

CodePudding user response:

I was going to use async/await but since there's that odd replacing before the JSON gets parsed I've reverted to old-school fetch with "thenables".

function ajaxLogoutDetailsApi() {
  
  const endpoint = 'OIDCGetLogoutDetails';
  
  // Fetch the JSON
  fetch(endpoint)

    // This is returned as the first argument
    // of "then"
    .then(json => {

      // Weird replacement stuff
      const updated = json
        .replace('\/\*', '')
        .replace('\*\/', '');

      // Parse the JSON
      const data = JSON.parse(updated);

      // Set the new page if the condition is met
      if (data.logoutUrl) {
        window.location.href = data.logoutUrl;
      }

    })

    // Catch any errors
    .catch(error => {
      console.error('Error:', error);
    });

}

  • Related