我使用 HTML、Javascript 和 bootstrap 来构建 Web 应用程序,但遇到了困难,我尝试使用 document.getElementById("input here")
但只返回了一个 0 的数组。我想要从 api 获取数据,然后将其显示在媒体列表上,我尝试使用搜索栏作为使用关键字过滤 api GET 的方式,因为我读到这在我使用的 api 中是可能的。
$(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
}
});
});
输入的 HTML:
<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 缺少一些 div
结尾以及您的 JS。 (至少是您粘贴到此处的片段)。
我已经构建了这个 JSFiddle测试它并且它有效。
只需更改:
url: 'https://…&q=' + word
至:
url: 'https://…&q=' + word.value
您的 API 调用有效并且正在响应:
{"message":"Invalid Mashape Key"}
这完全符合逻辑,因为您需要将“KEY HERE”部分替换为真正的 key 。检查Mashape Keys
xhr.setRequestHeader("X-Mashape-Authorization", "KEY HERE");
关于javascript - 如何从 Bootstrap 搜索栏获取输入并将其放入 ajax 调用中以检索数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40808400/