我对 JS 和 jQuery 还很陌生,但想知道如何从 JSON 文件中搜索和检索一些结果。
我的 html 看起来像这样:
<form name="fetch">
<input type="text" id="query">
<input type="submit" id="search" value="Go">
</form>
<section id="main"></section>
我的 JS 是这样的:
$(function() {
$.getJSON('data.json', function(data) {
var search = $('#query').val();
var output="<h2>Search results for " + search + "</h2>";
for (var i in data.places) {
for (var ind in data.places[i].service[0].type) {
if (data.places[i].service[0].type[ind].name == search) {
output+="<h3>" + data.places[i].name + "</h3>";
} else {}
};
};
document.getElementById("main").innerHTML=output;
});
$('#fetch form').on('submit', data);
});
我将输入字段的值存储在名为 search
的变量中,但是当我 git“Go”时,它似乎没有给我任何结果。但是,如果我使用 JSON 对象中的 value=""
属性对 HTML 中的 input
字段进行硬编码,则会返回数据。
我只是不知道如何保存在搜索变量中输入的内容并使用该函数返回结果。
感谢任何帮助。
提前致谢!
更新:下面附上一些 JSON 数据:
{
"places":[
{
"name": "The Whittington Hospital",
"service": [{
"type": [
{ "name": "Hernia Repair" },
{ "name": "Hip Replacement" },
{ "name": "Crohn's Disease" },
{ "name": "Pregnancy" }
]
}]
},
{
"name": "University College Hospital",
"service": [{
"type": [
{ "name": "Hernia Repair" },
{ "name": "Pregnancy" }
]
}]
}
]
}
最佳答案
$('#fetch form').on('submit', data);
很可能是错误的(代码中没有名为 data
的方法)
您可能需要这个
$(function() {
function performSearch(e){
e.preventDefault();
$.getJSON('data.json', function(data) {
var search = $('#query').val();
var output="<h2>Search results for " + search + "</h2>";
for (var i in data.places) {
for (var ind in data.places[i].service[0].type) {
if (data.places[i].service[0].type[ind].name == search) {
output+="<h3>" + data.places[i].name + "</h3>";
} else {}
};
};
document.getElementById("main").innerHTML=output;
});
};
$('#fetch').on('submit', performSearch);
});
<小时/>
或者(因为您的 JSON 是静态的并且您在客户端进行搜索)
$(function() {
var data;
$.getJSON('data.json', function(jsondata) { data = jsondata; });
function performSearch(e){
e.preventDefault();
if (data == undefined) return; // do nothing if json is not yet loaded
var search = $('#query').val();
var output="<h2>Search results for " + search + "</h2>";
for (var i in data.places) {
for (var ind in data.places[i].service[0].type) {
if (data.places[i].service[0].type[ind].name == search) {
output+="<h3>" + data.places[i].name + "</h3>";
} else {}
};
};
document.getElementById("main").innerHTML=output;
};
$('#fetch').on('submit', performSearch);
});
<小时/>
更新
几个错误:
-
$('#fetch form')
将表单定位在id="fetch"
元素下。- 但你使用
name
而不是id
所以处理程序没有绑定(bind) name
(应该是id
)属性存在于表单本身,而不是其父级。
- 但你使用
所以你需要将html更改为<form id="fetch">
和 jquery 直接绑定(bind)到它 $('#fetch').on('submit', performSearch);
关于javascript - 从 JSON 数据库检索结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25109691/