如何从引导搜索栏获取输入并将其放入ajax调用以检索数据?

时间:2016-11-25 15:40:10

标签: javascript html json twitter-bootstrap

我使用HTML,Javascript和bootstrap来构建一个Web应用程序并且已经碰壁了,我尝试使用$(document).ready(function(){ $("button").click(function(){ var word = document.getElementById("sbar"); $.ajax({ url: 'https://community-food2fork.p.mashape.com/search?key=0ee5a01caf7f7c3512b54978628f1a4e&q=' + word, // The URL to the API. You can get this in the API page of the API you intend to consume type: 'GET', // The HTTP Method, can be GET POST PUT DELETE etc data: {}, // Additional parameters here dataType: 'json', success: function(data) { search = JSON.parse(JSON.stringify(data.recipes)); console.dir(search); }, error: function(err) { alert(err); }, beforeSend: function(xhr) { xhr.setRequestHeader("X-Mashape-Authorization", "KEY HERE"); // Enter here your Mashape key } }); }); 但是只返回了一个0的数组。我想从api中获取数据然后显示它在媒体列表上,我试图使用搜索栏作为过滤api GET的关键词的方式,因为我已经阅读过,这可以在api即时使用。

<div class="container">
    <div style="background: rgba(60, 255, 60, 0.2);" class="jumbotron">
        <h1>Meal Manager</h1>
        <p class="lead">A simple recipe app that provides ingerdiants fast.</p>
        <div class="input-group">
            <input type="text" id="sbar" class="form-control" aria-label="...">
            <div class="input-group-btn">
                <button type="button" class="btn btn-default" id="button" title="Search Database">
                    <span class="glyphicon glyphicon-search" aria-hidden="true"></span>
                </button>
                <button type="button" class="btn btn-default btn" title="Sort by reviews" >
                    <span class="glyphicon glyphicon-star" aria-hidden="true"></span>
                </button>
                <button type="button" class="btn btn-default btn" title="Sort by trending" >
                    <span class="glyphicon glyphicon-hand-up" aria-hidden="true"></span>
                </button>
            </div>
        </div>

输入的HTML:

for(int i = 0; i < pChain.Count(); i++)
{
    // If the amount(Count) of SequenceEqual lists in pChain for the current iteration 
    // of pChain (pChain[i]) is > 1
    if (pChain.Count(l => l.SequenceEqual(pChain[i])) > 1)
        pChain.RemoveAt(i);
}

1 个答案:

答案 0 :(得分:0)

你的代码几乎没问题。 HTML缺少一些div结束以及你的JS。 (至少你在这里粘贴的片段)

我已经构建了这个JSFiddle来测试它并且它有效。

只需改变:

url: 'https://…&q=' + word

为:

url: 'https://…&q=' + word.value

您的API调用有效并且它正在响应:

  

{&#34; message&#34;:&#34;无效的Mashape Key&#34;}

这完全是逻辑的,因为您需要替换真实密钥的"KEY HERE"部分。查看Mashape Keys

xhr.setRequestHeader("X-Mashape-Authorization", "KEY HERE");