我有一个简单的实时搜索设置,我无法排除故障。我是JSON的新手,但对html和jquery相当熟悉,但是我会在这里包含所有代码。没有错误,结果只是根本不显示我输入。首先是html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<title>JSON live search</title>
<link rel="stylesheet" href="mystyle.css"/>
</head>
<body>
<div id="searcharea">
<label for="search">Live search</label>
<input type="search" name="search" id ="search" placeholder="start typing.." />
</div>
<div id="update"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="script.js"></script>
</body>
</html>
和js:
$.getJSON('data.json', function(data) {
var output = '<ul class="searchresults">';
$.each(data, function(key, val) {
output += '<li>';
output += '<h2>' + val.name + '</h2>';
output += '</li>';
});
output += '</ul'>;
$('#update').html(output);
});
我按以下方式构建了JSON数据文件:
{
"businesses":[
{"name":"LJMU","contacts":[{"contacts":"con1"},{"contacts":"con2"},{"contacts":"con3"}]},
{"name":"Bobs bricks","contacts":[{"contacts":"con1"},{"contacts":"con2"},{"contacts":"con3"}]},
{"name":"Apple","contacts":[{"contacts":"con1"},{"contacts":"con2"},{"contacts":"con3"}]},
]
}
我知道这是一种痛苦,但任何人都可以建议我为什么看不到结果?
答案 0 :(得分:0)
不应该output += '<h2>' + val.name + '</h2>';
是
output += '<h2>' + val.businesses.name + '</h2>';
答案 1 :(得分:0)
您的json对象(data
)包含一个属性businesses
,即数组。因此,您必须使用$.each
而非data
,data.businesses
$.getJSON('data.json', function(data) {
var output = '<ul class="searchresults">';
$.each(data.businesses, function(key, val) {
output += '<li>';
output += '<h2>' + val.name + '</h2>';
output += '</li>';
});
output += '</ul'>;
$('#update').html(output);
});