“Javascript Pure Ajax Promise” Kode Jawaban

JavaScript berjanji dengan Ajax

function doTheThing() {
  return new Promise((resolve, reject) => {
    $.ajax({
      url: window.location.href,
      type: 'POST',
      data: {
        key: 'value',
      },
      success: function (data) {
        resolve(data)
      },
      error: function (error) {
        reject(error)
      },
    })
  })
}
Modern Mouse

JavaScript berjanji dengan Ajax

doTheThing()
  .then((data) => {
    console.log(data)
    doSomethingElse()
  })
  .catch((error) => {
    console.log(error)
  })
Modern Mouse

JavaScript berjanji dengan Ajax

function doTheThing() {
  $.ajax({
    url: window.location.href,
    type: 'POST',
    data: {
      key: 'value',
    },
    success: function (data) {
      console.log(data)
    },
    error: function (error) {
      console.log(error)
    },
  })
}
Bewildered Booby

Javascript Pure Ajax Promise

function getRequest(url) {
    return makeRequest('GET', url);
}

function postRequest(url, data) {
    return makeRequest('POST', url, data);
}

function makeRequest(method, url, data) {
    return new Promise(
        function(resolve, reject) {
            var http = new XMLHttpRequest();
            http.open(method, url);
            http.onload = function() {
                if (this.status >= 200 && this.status < 300) {
                    var response = http.response;
                    try {
                        response = JSON.parse(response);
                        resolve(response);
                    } catch (error) {
                        reject({
                            status: this.status,
                            statusText: error
                        });
                    }

                } else {
                    reject({
                        status: this.status,
                        statusText: http.statusText
                    });
                }
            };
            http.onerror = function() {
                reject({
                    status: this.status,
                    statusText: http.statusText
                });
            };

            if (method === 'POST') {
                data = data || new FormData();
                http.send((data));
            } else http.send();
        }
    );
}
Lucky Llama

Jawaban yang mirip dengan “Javascript Pure Ajax Promise”

Pertanyaan yang mirip dengan “Javascript Pure Ajax Promise”

Lebih banyak jawaban terkait untuk “Javascript Pure Ajax Promise” di JavaScript

Jelajahi jawaban kode populer menurut bahasa

Jelajahi bahasa kode lainnya