我创建了一个个人JSON文件,当我看到consolo.log可以正常工作但是如何从搜索按钮在浏览器上发布? 我无法找到一个很好的解释。 我必须在下面这4个地方连续显示4个小div。 用户只能搜索单词" places"我必须打印places.name,places.imgage_urls,places.location_name,places.day_price,places.review_count
这是我的代码:
<form>
<input type="text" name="search" placeholder="Find a place to work..">
<input id="submit" type="submit" name="subtim" value="Search">
</form>
`<div id="results"></div>`
的jQuery
$.getJSON("../test.json", function(data) {
console.log(data);
});
$.ajax({
url: "../test.json",
dataType: "json",
type: "get",
cache: false,
success: function(data) {
console.log(data);
$(data.places).each(function(index, value){
console.log(value);
});
}
});
JSON
{
"places": [
{
"id": 1,
"name": "HNK Flexplek",
"imgage_urls": "https://d2h37djvgj7smg.cloudfront.net/0b4a33ef924631441bc371646c6c3830592c746d/18995.600x400x16919.jpg",
"location_name": "HNK Amsterdam Houthavens",
"day_price": 175,
"review_count": 11
},
{
"id": 2,
"name": "Harrods",
"imgage_urls": "https://d2h37djvgj7smg.cloudfront.net/4efa8f4624286e1890bdcfc82e9dfb06ccfb77ad/9492.600x400x16919.jpg",
"location_name": "Het Warenhuis",
"day_price": 200,
"review_count": 4
},
{
"id": 3,
"name": "V2",
"imgage_urls": "https://d2h37djvgj7smg.cloudfront.net/cd6dfff88114b71ada941ff4e004b0cf143fdb3e/18996.600x400x16919.jpg",
"location_name": "HNK Amsterdam Houthavens",
"day_price": 260,
"review_count": 13
},
{
"id": 4,
"name": "LaFayette",
"imgage_urls": "https://d2h37djvgj7smg.cloudfront.net/6f5a44425fd3892f70755fed536885e0476fc6b8/2328.600x400x16919.jpg",
"location_name": "Het Warenhuis",
"day_price": 150,
"review_count": 0
}
]
}
答案 0 :(得分:1)
$("#find_place").submit(liveSearch);
$("[name=search]").on("keyup",liveSearch);
function liveSearch(){
var inp = $("[name=search]").val().toLoweCase();
$.ajax({
url: "../test.json",
dataType: "json",
type: "get",
cache: false,
success: function(data) {
console.log(data);
$.each(data.places, function(i, v){
if(v.name.toLoweCase().indexOf(inp)>-1 || v.name.toLoweCase() == inp){
$("results").append("<div id='place"+v.id+"' class='place'>"+
+"<h3>"+v.name+"</h3>"
+"<h5>"+v.location_name+"</h5>"
+"<img alt='"+v.location_name+"' title='"+v.location_name+"' src='"+v.imgage_urls+"'></img>"
+"<span>Day Price: "+v.day_price+"</span>"
+"<span>Review count: "+v.review_count+"</span>"
+"</div>");
}
});
}
})
return false;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id='find_place'>
<input type="text" name="search" placeholder="Find a place to work..">
<input id="submit" type="submit" name="subtim" value="Search">
</form>
<div id="results"></div>
&#13;
答案 1 :(得分:0)
在HTML中创建一个元素并为其指定一个ID。然后,当您的Ajax返回json文件的内容时,请使用id更改元素的innerhtml。
答案 2 :(得分:0)
为了在表单中包含JSON值,您需要将其存储在表单元素中。此外,由于所有JSON都是表单中的单个值,因此需要将其序列化为单个字符串。
在表单中添加表单元素:
<input type="hidden" name="someName" id="someId" />
然后设置其值:
$.getJSON("../test.json", function(data) {
$('#someId').val(JSON.stringify(data));
});