Как получить несколько ответов AJAX в одной функции - PullRequest
0 голосов
/ 22 марта 2019

Я не знаю, возможно ли это, но я пытаюсь получить несколько ответов ajax и получить доступ к его значениям в другой функции.

Я на самом деле получаю ответы (по два раза в каждом), но яне может вернуть ответы отдельные значения.

JSFiddle

function firstResponse() {
  const response1 = $.ajax({
    url: 'https://cors-anywhere.herokuapp.com/http://api.icndb.com/jokes/random',
    method: 'GET',
    contentType: 'application/json',
  });

  response1.done(function(response1) {
    test(response1);
  })
}

function secondResponse() {
  const response2 = $.ajax({
    url: 'https://cors-anywhere.herokuapp.com/https://official-joke-api.appspot.com/random_joke',
    method: 'GET',
    contentType: 'application/json',
  });

  response2.done(function(response2) {
    test(response2);
  })
}

firstResponse();
secondResponse();

function test(response1, response2) {
  console.log('Response 1', response1);
  console.log('Response 2', response2);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Ответы [ 3 ]

1 голос
/ 22 марта 2019

Существуют различные способы достижения этого.Лично я бы пошел с promises.

function firstResponse() {
  return $.ajax({
    url: 'https://cors-anywhere.herokuapp.com/http://api.icndb.com/jokes/random',
    method: 'GET',
    contentType: 'application/json'
  });
}

function secondResponse() {
  return $.ajax({
    url: 'https://cors-anywhere.herokuapp.com/https://official-joke-api.appspot.com/random_joke',
    method: 'GET',
    contentType: 'application/json'
  });
}

function test() {
  Promise.all([
    firstResponse(), 
    secondResponse()
  ]).then(result => {
    console.log(result);
  });
}

test();

В функции test вы вызываете Promise.all, который ожидает разрешения всех индивидуальных обещаний и выводит результат в виде массива в порядкеОбещания, переданные ему во время звонка.

0 голосов
/ 22 марта 2019
let urls = ['https://cors-anywhere.herokuapp.com/http://api.icndb.com/jokes/random',
    'https://cors-anywhere.herokuapp.com/https://official-joke-api.appspot.com/random_joke'];

let structure = {
    method: 'GET',
    contentType: 'application/json',
};

async function first() {
    try {
        const response = await $.ajax({
            url: urls[0],
            structure,
        });

        return response;
    } catch(error) {
        // Error
    }

}

async function second() {
    try {
        const response = await $.ajax({
            url: urls[1],
            structure,
        });

        return response;
    } catch(error) {
        // Error
    }
}

async function test() {
    let response = await ('s')
    return response
}

first()
    .then(() => second());
0 голосов
/ 22 марта 2019

Ajax-вызовы являются асинхронными, поэтому, если вы хотите обработать два результата в одной функции, вы должны сделать счетчик самостоятельно, что-то вроде этого для простейшего вида:

function firstResponse() {
  const response1 = $.ajax({
    url: 'https://cors-anywhere.herokuapp.com/http://api.icndb.com/jokes/random',
    method: 'GET',
    contentType: 'application/json',
  });

  response1.done(function(response1) {
    test("response1", response1);
  })
}

function secondResponse() {
  const response2 = $.ajax({
    url: 'https://cors-anywhere.herokuapp.com/https://official-joke-api.appspot.com/random_joke',
    method: 'GET',
    contentType: 'application/json',
  });

  response2.done(function(response2) {
    test("response2", response2);
  })
}

var responses = [];

firstResponse();
secondResponse();

function test(index, data) {
  responses[index] = data;
  if (Object.keys(responses).length === 2) processResponses();
}

function processResponses() {
  console.log(responses);
}

Существуют различные более сложные способычтобы справиться с этим, например, используя async / await или что-то в этом роде, но это должно сделать вашу работу без особых изменений в существующем коде.

ОБНОВЛЕНИЕ: для асинхронного / ожидающего способа, который я предпочитаю делать в наше время:

(async () => {
  const response1 = await $.ajax({
    url: 'https://cors-anywhere.herokuapp.com/http://api.icndb.com/jokes/random',
    method: 'GET',
    contentType: 'application/json',
  });

  const response2 = await $.ajax({
    url: 'https://cors-anywhere.herokuapp.com/https://official-joke-api.appspot.com/random_joke',
    method: 'GET',
    contentType: 'application/json',
  });

  console.log(response1);
  console.log(response2);

})();
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...