【问题标题】:I want to search data from a api and show its result我想从 api 搜索数据并显示其结果
【发布时间】:2019-02-10 05:27:51
【问题描述】:

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
    })
;

【问题讨论】:

  • 到目前为止您尝试了什么?没有人能帮你解决这类问题。
  • 如何从api中获取数据,,,

标签: jquery node.js ajax search


【解决方案1】:

确保你按照自己的意愿应用 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>

把它放在你的脚本标签中

<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.log(searchResults.author_name);
               // console.log("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.log("Its author data"+authors.name);
        $('#authorlist').append('<li><a href="#" >'+name+'</a></li>')
    });
    $.each(Books, function(index,name) {
        console.log("Book Data"+books);
        $('#booklist').append('<li><a href="#" >'+name+'</a></li>')
    });
}

【讨论】:

    【解决方案2】:

    仅使用 HTML 代码是无法做到这一点的。当您提交表单时,表单输入将发送到服务器并刷新页面。在这种情况下,您无法处理服务器响应。

    如果您真的想在 Javascript 中获得响应(不刷新页面),那么您需要使用 AJAX,当您开始谈论使用 AJAX 时,您需要使用库。 jQuery 是迄今为止最流行的库。 jQuery 有一个名为 Form 的插件,它可以完全按照您的要求进行操作。

    例子:

    // wait for the DOM to be loaded 
    $(document).ready(function () {
        console.log("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>

    【讨论】:

      猜你喜欢
      • 2013-02-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-24
      相关资源
      最近更新 更多