Показать Bootstrap Popover с динамическим контентом на основе ответа API - PullRequest
1 голос
/ 30 октября 2019

Моя проблема довольно проста.
У меня есть кнопка, которая при нажатии показывает всплывающее окно.
Содержимое всплывающего окна не является статичным, но зависит от ответа API.
Я неЯ хочу вызвать этот API заранее, но когда нажата кнопка.

Я хочу что-то вроде этого: enter image description here

Содержимое свойства всплывающего окна принимает функцию
, поэтому я подумал вызвать API в нем, но затем я столкнулся с проблемой асинхронного вызова

Вот мой код: https://jsfiddle.net/5x43tcja/

$('a').popover({
    content: function(){
        var result;
        fetch('https://jsonplaceholder.typicode.com/todos/1')
            .then(response => response.json())
            .then(function(json){
                result = json.title;
            });
        return result; //The result here is undefined. But what I want is "delectus aut autem" that comes from the API.

    }
});

Я пытался использовать async / await, но все же я не получил желаемый результат: https://jsfiddle.net/jmn7abqz/

async function getData(){
    var resultFetch = await fetch('https://jsonplaceholder.typicode.com/todos/1');
    console.log("resultFetch", resultFetch);
    return resultFetch;
}

$('a').popover({
    content: function(){
        var result = getData();
        return result;

    }
});

Как я могу это сделать?

Примечание

Я использую Bootstrap v3.3.7

1 Ответ

0 голосов
/ 30 октября 2019

Использование show.bs.popover событие

$('a').popover({
  content: 'Loading...'
}).one('show.bs.popover', function(e) {
  fetch('https://jsonplaceholder.typicode.com/todos/1')
    .then(response => response.json())
    .then(function(json) {
      $(e.target).popover('dispose').popover({
        content: json.title
      }).popover('show');
    });
});

https://jsfiddle.net/aswinkumar863/erkzo7as/

...