[英]access nested json data from ajax call
我正在与一个API交互,该API向我返回JSON数据。 由于结果不是存储在文件中,而是存储在服务器内存中,因此我很难确定如何访问数据并将其写入html网页。 这是我的$ .ajax调用的样子:
$.ajax({
type: "post",
url:"https://www.xxx/v1/trips/search? key=xxxx",
data:JSON.stringify({request : requestTrav1Dest1}),
dataType:"json",
success:successFunction,
headers:{"Content-Type":"application/json"}
});
这是我从服务器获取的JSON的样子:
{
"kind": "#tripsSearch",
"trips": {
"kind": "#tripOptions",
"tripOption": [
{
"saleTotal": "USD294.10",
"id": "DMfSXrkVQGKTVQsDD5l60N004",
},
"saleTotal": "USD333.10",
"id": "DMfSXrkVQGKTVQsDD5l60N002",
},
{
"saleTotal": "USD225.94",
"id": "DMfSXrkVQGKTVQsDD5l60N005",
}
]
}
}
我真正需要的是每个tripOption的saleTotal。
我打破了在查询成功的情况下运行的功能:
function successFunction(servResponse){
$('#content').load('resultsPage.html #content');
var newContent = '';
for(var i = 0; i < servResponse.trips.tripOption[i].length; i++){
newContent += '<div class="results">';
newContent += '<p>' + "Option " + (i+1) + '<br>';
newContent += servResponse.trips.tripOption[0].saleTotal + '<br>';
newContent += '</div>';
}
document.getElementById('content').innerhtml = newContent;
}
不幸的是,这没有将任何内容写到网页上。 到目前为止,我只能在Chrome开发者工具栏控制台中查看原始JSON结果。
有人可以帮忙确定我需要做些什么吗? 提前致谢!
假设页面上有一个元素,其ID为content
,则它应该可以正常工作,只是有一点错字
document.getElementById('content').innerhtml = newContent;
大写“ HTML”,
document.getElementById('content').innerHTML = newContent;
$('#content').load('resultsPage.html #content');
看起来不正确,第一个参数应该只是一个URL。 暂时将其注释掉,因为您要更改另一行的内容。
另外,第四行应为:
for(var i = 0; i < servResponse.trips.tripOption.length; i++){
你有:
... tripOption[i].length ...
以下功能应:
这是你想要的吗? 您当前应用于.results
的CSS可能需要改为应用于.results p
。
function successFunction(servResponse){
var tripOption = servResponse.trips.tripOption;
var newContent = '<div class="results">';
for(var i = 0; i < tripOption.length; i++){
newContent += '<p>' + "Option " + (i+1) + '<br>';
newContent += tripOption[i].saleTotal + '<p>';
}
newContent += '</div>';
document.getElementById('content').innerHTML = newContent;
}
var servResponse = {
"kind": "#tripsSearch",
"trips": {
"kind": "#tripOptions",
"tripOption": [
{
"saleTotal": "USD294.10",
"id": "DMfSXrkVQGKTVQsDD5l60N004",
},{
"saleTotal": "USD333.10",
"id": "DMfSXrkVQGKTVQsDD5l60N002",
},
{
"saleTotal": "USD225.94",
"id": "DMfSXrkVQGKTVQsDD5l60N005",
}
]
}
};
function successFunction(servResponse) {
var newContent = '';
servResponse.trips.tripOption.forEach(function(el,index){
newContent += '<div class="results">';
newContent += '<p>' + "Option " + (index+1) + '<br>';
newContent += el.saleTotal + '<br>';
newContent += '</div>';
console.log(el.saleTotal);
});
document.getElementById('content').innerHTML = newContent;
}
successFunction(servResponse);
Using pure javascript forEach loop
Example Link : http://jsfiddle.net/c1wzsqaf/1/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.