我试图找出当行项遇到一个变量或按钮单击时传递的变量时如何选择特定的JSON对象。到目前为止,我得到它的工作,但它说[对象],[对象]。我相信这是因为它以数组形式返回。我错过了什么?
var Type = "Champagne";
$(document).ready(function(){
$("button").click(function(){
$("#data-details").empty();
$.get("working-data-file.json",{Type: Type},function(result){
$.each(result.data, function(i, field){
$("#data-details").append(this.objects.Title);
});
});
});
});
.JSON文件如下所示:
{"objects":
[
{
"Type": "Champagne",
"Sweetness": "Brut",
"Producer": "Dom Perignon",
"Vintage": "2006",
"Recommendation": "Classic",
"Data": "12.29.2012",
"Title": "The wine’s opulence – contained and succulent, round at heart – reveals itself in the mouth."
},
{
"Type": "Cava",
"Sweetness": "Brut-Nature",
"Producer": "Canals Canals",
"Vintage": "2014",
"Recommendation": "Preferred",
"Data": "12.29.2012",
"Title": "2nd Cava."
}
]
}
你可以用每个jquery循环。
$( document ).ready(function() {
$('#button').click(function(e){
$.each(data.objects, function( i, item) {
$("#data-details").append('<p>' + item.Title + '</p>');
});
})
});
var data = {"objects":
[
{
"Type": "Champagne",
"Sweetness": "Brut",
"Producer": "Dom Perignon",
"Vintage": "2006",
"Recommendation": "Classic",
"Data": "12.29.2012",
"Title": "The wine’s opulence – contained and succulent, round at heart – reveals itself in the mouth."
},
{
"Type": "Cava",
"Sweetness": "Brut-Nature",
"Producer": "Canals Canals",
"Vintage": "2014",
"Recommendation": "Preferred",
"Data": "12.29.2012",
"Title": "2nd Cava."
}
]
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type=button id="button" value="click me"/>
<div id="data-details"></div>
尝试:
var result={"objects":
[
{
"Type": "Champagne",
"Sweetness": "Brut",
"Producer": "Dom Perignon",
"Vintage": "2006",
"Recommendation": "Classic",
"Data": "12.29.2012",
"Title": "The wine’s opulence – contained and succulent, round at heart – reveals itself in the mouth."
},
{
"Type": "Cava",
"Sweetness": "Brut-Nature",
"Producer": "Canals Canals",
"Vintage": "2014",
"Recommendation": "Preferred",
"Data": "12.29.2012",
"Title": "2nd Cava."
}
]
}
Object.keys(result).forEach(key => {
let value = result[key];
console.log(value[0].Title);
})
[关键]})