美好的一天, 我正在尝试运行一个简单的getJSON来从数据json获取信息,差不多已经完成但是在运行时,在html中得到未定义
这是我的jquery:
$(document).ready( function() {
$.getJSON("/airport.json?code=bgw", function(data) {
$('#stage').html('<p> Name: ' + data.result.request.code + '</p>');
$.each(data.result.response.airport.pluginData.schedule.arrivals.data, function() {
$("ul").append("<li>Name: "+this['flight.status.text']+"</li><br />");
});
});
});
数据json:
` {
"result": {
"response": {
"airport": {
"pluginData": {
"schedule": {
"arrivals": {
"data": [
{
"flight": {
"status": {
"live": true,
"text": "Estimated 13:44",
"icon": "green",
"estimated": null,
"ambiguous": false
}
}
}
]
}
}
}
}
}
}
}
`
关于我可能做错的任何想法?
答案 0 :(得分:1)
您正在以this['flight.status.text']
的形式访问嵌套对象。我相信你想做this.flight.status.text
。请参阅以下差异
var data = [{
test: {
deep: {
nested: {
object: 1
}
}
}
}, {
test: {
deep: {
nested: {
object: 2
}
}
}
}];
console.log("Not working");
$.each(data, function() {
console.log(this['test.deep.nested.object']);
});
console.log("--------------");
console.log("Working");
$.each(data, function() {
console.log(this.test.deep.nested.object);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
另外,根据您的JSON,data.result.request.code
不存在。
答案 1 :(得分:1)
使用this.flight.status.text
显示如下文字
$(document).ready( function() {
data={
"result": {
"response": {
"airport": {
"pluginData": {
"schedule": {
"arrivals": {
"data": [
{
"flight": {
"status": {
"live": true,
"text": "Estimated 13:44",
"icon": "green",
"estimated": null,
"ambiguous": false
}
}
}
]
}
}
}
}
}
}
};
$('#stage').html('<p> Name: ' + 'bgw' + '</p>'); $.each(data.result.response.airport.pluginData.schedule.arrivals.data, function(){
$("ul").append("<li>Name: "+this.flight.status.text+"</li><br />");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="stage"></div>
<ul></ul>