Я хочу найти данные из api и показать его результат

Html-код, строка передается в q, теперь я не знаю, как получить данные на моем интерфейсе.

 <div class = "ui search">
   <form class = "example" action = "/dashboard" method = "get">
<input type = "text" placeholder = "Enter The Book Name to Search" class = "prompt" name = "q">
    <button type = "submit"><i class = "fa fa-search"></i></button>
</form>
    <div class = "results"></div>
</div>

Как написать тег scipt, как получить данные из api пожалуйста, помогите ребятам

ссылка: https://openlibrary.org/search?q= {строка запроса}

<script>

$('.ui.search')
    .search({
        apiSettings: {
            url: 'https://openlibrary.org/search?q = {query}'
        },
        fields: {
            results : 'items',
            title   : 'name',
            url     : 'html_url'
        },
        minCharacters : 3
    })
;

Что вы пробовали до сих пор? Никто не может вам помочь с таким вопросом.

CodeThing 05.09.2018 09:01

Как получить данные из api ,,

EasyFreeNotes 05.09.2018 09:03
Как конвертировать HTML в PDF с помощью jsPDF
Как конвертировать HTML в PDF с помощью jsPDF
В этой статье мы рассмотрим, как конвертировать HTML в PDF с помощью jsPDF. Здесь мы узнаем, как конвертировать HTML в PDF с помощью javascript.
4
2
319
2
Перейти к ответу Данный вопрос помечен как решенный

Ответы 2

Вы не сможете сделать это, используя только HTML-код. Когда вы отправляете форму, входные данные формы отправляются на сервер, и страница обновляется. В этом случае вы не сможете обработать ответ сервера.

Если вы действительно хотите получить ответ в Javascript (без обновления страницы), тогда вам нужно будет использовать AJAX, а когда вы начнете говорить об использовании AJAX, вам понадобится библиотека. jQuery - безусловно, самая популярная библиотека. Для jQuery есть плагин Форма, который будет делать именно то, что вам кажется.

Пример:

// wait for the DOM to be loaded 
$(document).ready(function () {
    console.info("Thank you for your 1!");
    // bind 'myForm' and provide a simple callback function 
    // attach handler to form's submit event 
        $('#myForm')
      .ajaxForm({
          url : $('#myForm').attr('action'), // or whatever
          dataType : 'json',
          success : function (response) {
              alert("The server says: " + JSON.stringify(response));
          }
      });
});
<script src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src = "http://malsup.github.com/jquery.form.js"></script>

<form id = "myForm" action = "https://httpbin.org/get" method = "get"> 
    Name: <input type = "text" name = "name" /> 
    Comment: <textarea name = "comment"></textarea> 
    <input type = "submit" value = "Submit Comment" /> 
</form>
Ответ принят как подходящий

Убедитесь, что вы применили css по своему желанию, это будет работать для получения данных.

<div id = "multiple-datasets">
            <form class = "example" action = "#">
        <input class = "typeahead" type = "text" placeholder = "Enter The Book Name to Search" name = "search">
            </form>
        </div>

put this in your script tag

<script>
var books = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace,
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    remote: {
        url: 'http://openlibrary.org/search.json?title=%QUERY',
        wildcard: '%QUERY',
        filter: function (searchResults) {
            return $.map(searchResults.docs, function (searchResults) {
              //  console.info(searchResults.author_name);
               // console.info("key is "+searchResults.key)
                if (JSON.parse(sessionStorage.getItem("selectedBooks") == undefined || JSON.parse(sessionStorage.getItem("selectedBooks").indexOf(searchResults.title)) == -1)){
                    return {
                        title: searchResults.title,
                        key: searchResults.key,
                    };
                }
            });
        }
    }
});
var authorsList = [];
var authors = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace,
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    remote: {
        url: 'http://openlibrary.org/search.json?author=%QUERY',
        wildcard: '%QUERY',
        filter: function (searchResults) {
            return $.map(searchResults.docs, function (searchResults) {
                if (searchResults.author_name !== undefined){
                    var author = searchResults.author_name.toString();
                }
                if (authorsList.indexOf(author) == -1) {
                    authorsList.push(author);
                    return {
                        author_key: searchResults.author_key,
                        author: author,
                    };
                }
            });
        },
    }
});
$('#multiple-datasets .typeahead').typeahead({
        highlight: true
    },
    {
        name: 'books',
        display: 'title',
        source: books,
        templates: {
            header: '<h3 class = "search">Books</h3>'
        }
    },
    {
        name: 'authors',
        display: 'author',
        source: authors,
        templates: {
            header: '<h3 class = "search">Authors</h3>'
        }
    });

$('#multiple-datasets').bind('typeahead:selected', function(obj, datum, name) {
    if (name == 'books'){
        var selectedBooks = JSON.parse(sessionStorage.getItem("selectedBooks"));
        if (selectedBooks == null){
            var a = [];
            a.push(datum.title);
            sessionStorage.setItem("selectedBooks", JSON.stringify(a));
        }else{
            selectedBooks.push(datum.title);
            sessionStorage.setItem("selectedBooks", JSON.stringify(selectedBooks));
        }

    }else if (name == 'authors'){

        var selectedAuthors = JSON.parse(sessionStorage.getItem("selectedAuthors"));
        if (selectedAuthors == null){
            var a = [];
            a.push(datum.author);
            sessionStorage.setItem("selectedAuthors", JSON.stringify(a));
        }else{
            selectedAuthors.push(datum.author);
            sessionStorage.setItem("selectedAuthors", JSON.stringify(selectedAuthors));
        }
    }
    $('.typeahead').typeahead('val','');
    update_lists(JSON.parse(sessionStorage.getItem("selectedAuthors")),JSON.parse(sessionStorage.getItem("selectedBooks")));
});

update_lists(JSON.parse(sessionStorage.getItem("selectedAuthors")),JSON.parse(sessionStorage.getItem("selectedBooks")));



function update_lists(Authors,Books) {
    $('#authorlist li').remove();
    $('#booklist li').remove();
    $.each(Authors, function(index,name) {
       // console.info("Its author data"+authors.name);
        $('#authorlist').append('<li><a href = "#" >'+name+'</a></li>')
    });
    $.each(Books, function(index,name) {
        console.info("Book Data"+books);
        $('#booklist').append('<li><a href = "#" >'+name+'</a></li>')
    });
}

Другие вопросы по теме