这是代码,
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script >
$(document).ready(function($) {
// First link out of three
var url = 'https://www.sciencebase.gov/catalog
/items?parentId=504108e5e4b07a90c5ec62d4&max=60&offset=0&format=jsonp';
$.ajax({
type: 'GET',
url: url,
jsonpCallback: 'getSBJSON',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
for (var i = 0; i < json.items.length; i++) {
var urlId = json.items[i].id;
}
var linkBase = "http://www.sciencebase.gov/catalog/item/";
var link = "";
$.each(json.items, function(i,item){
link = linkBase + this.id
$('#sbItems').append('<li><b><a href="' + link + '">' +
this.title + '</a> - </b>' + this.summary + '</li>');
});
// devHack, loop being used to extract the exact id to use in url of
next ajax request
for (var i = 23; i < 24; i++) {
var urlId = json.items[i].id;
}
var itemLnkId = urlId;
$.ajax({
type: 'GET',
//url: 'https://www.sciencebase.gov/catalog/itemLink/' +
itemLnkId + '?format=jsonp',
//url: 'https://www.sciencebase.gov/catalog
/item/504216b6e4b04b508bfd333b?format=jsonp&fields=relationships,title,body,contacts',
url: 'https://www.sciencebase.gov/catalog/item/' + itemLnkId +
'?format=jsonp&fields=relationships,title,body,contacts',
jsonpCallback: 'getSBJSON',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
// devHack, setup for all links
var linkBase = "http://www.sciencebase.gov/catalog
/item/";
// devHack, will be used along with linkbase to get
to a specific link
var link = "";
$(function() {
$('#sbItems a').live('click',function(e) {
e.preventDefault();
$.each(json, function(i,item){
// devHack, will be used along with
linkbase to get to a specific link
link = "";
$('#sbItems').append('<li><a href="' +
link + '">' + json.relationships.links[0].title + '</a></li>');
});
//alert();
//$('#article').load( this.href );
});
});
/* $.each(json, function(i,item){
link = linkBase + this.relatedItemId
$('#sbItems').append('<li><a href="' + link +
'">' + this.title + '</a></li>');
}); */
},
error: function(e) {
console.log(e.message);
}
});
},
error: function(e) {
console.log(e.message);
}
});
});
</script>
</head>
<body>
<p><em>This is a simple example of a basic HTML page that uses JQuery to call items
from ScienceBase in JSON format and output them on the page. It serves to show how a
basic web application can interact with dynamic ScienceBase services. The code points
out the one critical feature of such an application, the use of a callback method in
the Javascript to allow web pages on one domain to call and render JSON from another
domain (www.sciencebase.gov). The listing below comes from a query for items under a
particular ScienceBase parent item - a set of project records from the USGS National
Research Program. The listing shows title with a link to the full project record in
ScienceBase and summary (first part of a full abstract). View source for code examples
and inline comments.</em></p>
<h3>Projects of the USGS Water National Research Program</h3>
<div class='wrapper'>
<ul id='sbItems'></ul>
</div>
</body>
</html>
由于“json.relationships.links [0] .title”,我的第二个.ajax()请求无法正常工作,但我已尽力尝试访问我所知道的标题。
我想要访问的信息位于:
我做错了什么? 代码应该在点击其中一个链接后打印第一个标题(虽然我真的需要打印所有这些标题)10次或更多次。
另外,在$ .each中我需要另一个循环来打印所有标题吗?
感谢您的帮助!
答案 0 :(得分:0)
虽然我无法解释为什么正在发生,正在发生什么很明显。简而言之,json API返回的数据与jsonp API不同。
从json API(漂亮的)返回的数据包含您预期的json.relationships.links[0].title
:
{
"link": {
"rel": "self",
"url": "https://www.sciencebase.gov/catalog/item/504216b6e4b04b508bfd333b"
},
"relatedItems": {
"link": {
"url": "https://www.sciencebase.gov/catalog/itemLinks?itemId=504216b6e4b04b508bfd333b",
"rel": "related"
}
},
"relationships": {
"total": 59,
"links": [{
"url": "https://www.sciencebase.gov/catalog/item/4f4e4b19e4b07f02db6a7f04",
"rel": "related",
"title": "Computation and analysis of the instantaneous-discharge record for the Colorado River at Lees Ferry, Arizona : May 8, 1921, through September 30, 2000",
"annotation": null
}, {
"url": "https://www.sciencebase.gov/catalog/item/5047afb7e4b067bd38f7f63d",
"rel": "related",
"title": "Multi-scale measurements and modeling of denitrification in streams with varying flow and nitrate concentration in the upper Mississippi River basin, USA",
"annotation": null
}, {
"url": "https://www.sciencebase.gov/catalog/item/5047afb8e4b067bd38f7f66f",
"rel": "related",
"title": "Characterization of microtopography and its influence on vegetation patterns in created wetlands",
"annotation": null
}, {
"url": "https://www.sciencebase.gov/catalog/item/5047afb8e4b067bd38f7f64f",
"rel": "related",
"title": "Fractal Topography and Subsurface Water Flows from Fluvial Bedforms to the Continental Shield",
"annotation": null
}, {
"url": "https://www.sciencebase.gov/catalog/item/4f4e4af1e4b07f02db691820",
"rel": "related",
"title": "Surface-Water and Ground-Water Interactions in the Central Everglades, Florida",
"annotation": null
}, {
"url": "https://www.sciencebase.gov/catalog/item/5047afb8e4b067bd38f7f67b",
"rel": "related",
"title": "Morphologic and Transport Properties of Natural Organic Floc",
"annotation": null
}, {
"url": "https://www.sciencebase.gov/catalog/item/5047afb8e4b067bd38f7f673",
"rel": "related",
"title": "Volunteer Monitoring Demonstrates Tree Planting Help Stream Ecosystems: Northern Virginia Soil and Water Conservation District",
"annotation": null
}, {
"url": "https://www.sciencebase.gov/catalog/item/5047afb8e4b067bd38f7f653",
"rel": "related",
"title": "Ground-based thermography of fluvial systems at low and high discharge reveals potential complex thermal heterogeneity driven by flow variation and bioroughness",
"annotation": null
}, {
"url": "https://www.sciencebase.gov/catalog/item/5047afb7e4b067bd38f7f641",
"rel": "related",
"title": "A complex-systems approach to predicting effects of sea level rise and nitrogen loading on nitrogen cycling in coastal wetland ecosystems",
"annotation": null
}, {
"url": "https://www.sciencebase.gov/catalog/item/5047afb8e4b067bd38f7f659",
"rel": "related",
"title": "Drag coefficients for modeling flow through emergent vegetation in the Florida Everglades",
"annotation": null
}]
},
"id": "504216b6e4b04b508bfd333b",
"title": "Hydrologic, Ecological, and Biogeochemical Processes in Flowing Waters",
"body": "<p> <\/p> \n<p style=\"color: rgb(0, 0, 0); font-family: Verdana, Arial, Helvetica, sans-serif; font-size: small; line-height: normal; \"> There is increasing recognition that the ecological function of rivers, streams, and wetlands are inseparable from the physics of flowing water and its interactions with the aquatic, terrestrial, and subsurface components that delineate the “river and wetland corridor”. It is the interplay between ecological, geomorphic, hydrologic, and biogeochemical processes that determines ecosystem function. These factors strongly influence how water quality and quality of aquatic and riparian habitat respond to human disturbances and changing climate. Improved conservation and restoration of river and wetland corridors requires an integrated approach that recognizes 1) linkages between surface and subsurface flows moving through terrestrial, riparian and aquatic components, and 2) feedbacks between flowing water and the geomorphic and ecological components that together modulate fluid flow, roughness, sediment entrainment and channel morphology in ways that further affect mass transfer of solutes and sediments between zones with different capacities for biogeochemical reactions. Many of the critical hydrologic and biogeochemical processes occur in complex aquatic environments at close proximity to the sediment interface, within periphyton layers, and on leaves of aquatic and emergent plants where processes are hidden from detection by standard sampling protocols. Our project addresses the profound need for new concepts, field methods, and cross-disciplinary models to address both the fundamental processes and their cumulative effects on basin-scale water quality and habitat value.<\/p> \n<p style=\"color: rgb(0, 0, 0); font-family: Verdana, Arial, Helvetica, sans-serif; font-size: small; line-height: normal; \"> Our project follows four main lines of investigation: (1) developing new concepts and tools to detect and quantify hydrologic fluxes, biogeochemical transformations, and interactions with ecological components within flowing surface waters, including highly episodic flows across floodplains and difficult to detect subsurface flows through hyporheic flow paths beneath stream channels, (2) estimating cumulative effects of those processes at larger (stream-reach and drainage basin) scales using natural and introduced tracers as well as improved and increasingly available data sets from airborne and satellite remote sensing to help integrate across the small-scale variability, (3) improving and advancing the use of numerical modeling codes for analyzing coupled terrestrial and aquatic ecological processes with surface and subsurface flow and transport phenomena, and 4) synthesizing a national-scale understanding of transport conditions in river and wetland corridors across gradients in climate, surficial geology, and human disturbance in the United States that influence residence time of water and fate of dissolved and fine particulate materials in the nation’s flowing waters. For additional information about this project, <i>see<\/i> <a href=\"http://water.usgs.gov/nrp/jharvey/\">project home page<\/a>.<\/p>",
"contacts": [{
"type": "Contact",
"name": "Office of the Chief Scientist for Water",
"highlighted": true,
"oldPartyId": 17096,
"email": null,
"phone": null,
"sourceId": null,
"title": null,
"address": null,
"addressType": null,
"city": null,
"state": null,
"zip": null,
"country": null,
"ttyPhone": null,
"faxPhone": null,
"hours": null,
"instructions": null,
"personsOrganization": null,
"organizationsPerson": null
}, {
"type": "Principal Investigator",
"name": "Judson W Harvey",
"highlighted": false,
"oldPartyId": 4306,
"email": "jwharvey@usgs.gov",
"phone": "703-648-5876",
"sourceId": null,
"title": null,
"address": null,
"addressType": null,
"city": null,
"state": null,
"zip": null,
"country": null,
"ttyPhone": null,
"faxPhone": null,
"hours": null,
"instructions": null,
"personsOrganization": null,
"organizationsPerson": null
}, {
"type": "Principal Investigator",
"name": "Laurel Larsen",
"highlighted": false,
"oldPartyId": 11859,
"email": "lglarsen@usgs.gov",
"phone": "703-648-5891",
"sourceId": null,
"title": null,
"address": null,
"addressType": null,
"city": null,
"state": null,
"zip": null,
"country": null,
"ttyPhone": null,
"faxPhone": null,
"hours": null,
"instructions": null,
"personsOrganization": null,
"organizationsPerson": null
}, {
"type": "Principal Investigator",
"name": "Harry L Jenter",
"highlighted": false,
"oldPartyId": 5071,
"email": "hjenter@usgs.gov",
"phone": "703-648-5916",
"sourceId": null,
"title": null,
"address": null,
"addressType": null,
"city": null,
"state": null,
"zip": null,
"country": null,
"ttyPhone": null,
"faxPhone": null,
"hours": null,
"instructions": null,
"personsOrganization": null,
"organizationsPerson": null
}]
}
而从jsonp API(漂亮的)返回的数据不是:
{
"link": {
"rel": "self",
"url": "https://www.sciencebase.gov/catalog/item/504216b6e4b04b508bfd333b"
},
"relatedItems": {
"link": {
"url": "https://www.sciencebase.gov/catalog/itemLinks?itemId=504216b6e4b04b508bfd333b",
"rel": "related"
}
},
"id": "504216b6e4b04b508bfd333b",
"title": "Hydrologic, Ecological, and Biogeochemical Processes in Flowing Waters",
"summary": " There is increasing recognition that the ecological function of rivers, streams, and wetlands are inseparable from the physics of flowing water and its interactions with the aquatic, terrestrial, and subsurface components that delineate the “river and wetland corridor”. It is the interplay between ecological, geomorphic, hydrologic, and biogeochemical processes that determines ecosystem function. These factors strongly influence how water quality and quality of aquatic and riparian habitat respond to human disturbances and changing climate. Improved conservation and restoration of river and wetland corridors requires an integrated approach that recognizes 1) linkages between surface and subsurface flows moving through terrestrial, [...]",
"body": "<p> <\/p> \n<p style=\"color: rgb(0, 0, 0); font-family: Verdana, Arial, Helvetica, sans-serif; font-size: small; line-height: normal; \"> There is increasing recognition that the ecological function of rivers, streams, and wetlands are inseparable from the physics of flowing water and its interactions with the aquatic, terrestrial, and subsurface components that delineate the “river and wetland corridor”. It is the interplay between ecological, geomorphic, hydrologic, and biogeochemical processes that determines ecosystem function. These factors strongly influence how water quality and quality of aquatic and riparian habitat respond to human disturbances and changing climate. Improved conservation and restoration of river and wetland corridors requires an integrated approach that recognizes 1) linkages between surface and subsurface flows moving through terrestrial, riparian and aquatic components, and 2) feedbacks between flowing water and the geomorphic and ecological components that together modulate fluid flow, roughness, sediment entrainment and channel morphology in ways that further affect mass transfer of solutes and sediments between zones with different capacities for biogeochemical reactions. Many of the critical hydrologic and biogeochemical processes occur in complex aquatic environments at close proximity to the sediment interface, within periphyton layers, and on leaves of aquatic and emergent plants where processes are hidden from detection by standard sampling protocols. Our project addresses the profound need for new concepts, field methods, and cross-disciplinary models to address both the fundamental processes and their cumulative effects on basin-scale water quality and habitat value.<\/p> \n<p style=\"color: rgb(0, 0, 0); font-family: Verdana, Arial, Helvetica, sans-serif; font-size: small; line-height: normal; \"> Our project follows four main lines of investigation: (1) developing new concepts and tools to detect and quantify hydrologic fluxes, biogeochemical transformations, and interactions with ecological components within flowing surface waters, including highly episodic flows across floodplains and difficult to detect subsurface flows through hyporheic flow paths beneath stream channels, (2) estimating cumulative effects of those processes at larger (stream-reach and drainage basin) scales using natural and introduced tracers as well as improved and increasingly available data sets from airborne and satellite remote sensing to help integrate across the small-scale variability, (3) improving and advancing the use of numerical modeling codes for analyzing coupled terrestrial and aquatic ecological processes with surface and subsurface flow and transport phenomena, and 4) synthesizing a national-scale understanding of transport conditions in river and wetland corridors across gradients in climate, surficial geology, and human disturbance in the United States that influence residence time of water and fate of dissolved and fine particulate materials in the nation’s flowing waters. For additional information about this project, <i>see<\/i> <a href=\"http://water.usgs.gov/nrp/jharvey/\">project home page<\/a>.<\/p>",
"provenance": {
"html": "Record was created from original web page content (see link)."
},
"dateCreated": "2012-09-01T08:07:51-06:00",
"lastUpdated": "2012-11-29T08:28:36-07:00",
"hasChildren": false,
"parentId": "504108e5e4b07a90c5ec62d4",
"contacts": [{
"type": "Contact",
"name": "Office of the Chief Scientist for Water",
"highlighted": true,
"oldPartyId": 17096,
"email": null,
"phone": null,
"sourceId": null,
"title": null,
"address": null,
"addressType": null,
"city": null,
"state": null,
"zip": null,
"country": null,
"ttyPhone": null,
"faxPhone": null,
"hours": null,
"instructions": null,
"personsOrganization": null,
"organizationsPerson": null
}, {
"type": "Principal Investigator",
"name": "Judson W Harvey",
"highlighted": false,
"oldPartyId": 4306,
"email": "jwharvey@usgs.gov",
"phone": "703-648-5876",
"sourceId": null,
"title": null,
"address": null,
"addressType": null,
"city": null,
"state": null,
"zip": null,
"country": null,
"ttyPhone": null,
"faxPhone": null,
"hours": null,
"instructions": null,
"personsOrganization": null,
"organizationsPerson": null
}, {
"type": "Principal Investigator",
"name": "Laurel Larsen",
"highlighted": false,
"oldPartyId": 11859,
"email": "lglarsen@usgs.gov",
"phone": "703-648-5891",
"sourceId": null,
"title": null,
"address": null,
"addressType": null,
"city": null,
"state": null,
"zip": null,
"country": null,
"ttyPhone": null,
"faxPhone": null,
"hours": null,
"instructions": null,
"personsOrganization": null,
"organizationsPerson": null
}, {
"type": "Principal Investigator",
"name": "Harry L Jenter",
"highlighted": false,
"oldPartyId": 5071,
"email": "hjenter@usgs.gov",
"phone": "703-648-5916",
"sourceId": null,
"title": null,
"address": null,
"addressType": null,
"city": null,
"state": null,
"zip": null,
"country": null,
"ttyPhone": null,
"faxPhone": null,
"hours": null,
"instructions": null,
"personsOrganization": null,
"organizationsPerson": null
}],
"webLinks": [{
"type": "webLink",
"typeLabel": "Web Link",
"uri": "http://water.usgs.gov/nrp/proj.bib/jharvey.html",
"title": "Original Web Page",
"hidden": false
}, {
"type": "webLink",
"typeLabel": "Web Link",
"uri": "http://water.usgs.gov/nrp/jharvey/",
"title": "Project Home Page",
"hidden": false
}],
"systemTypes": ["Folder"],
"tags": [{
"name": "Acid Mine Drainage"
}, {
"name": "Aquatic Habitat"
}, {
"name": "Contaminant Reactions and Transport"
}, {
"name": "Rivers and Streams"
}, {
"name": "Surface-water - Ground-water Interactions"
}, {
"name": "Wetlands"
}],
"spatial": {
"boundingBox": {
"maxY": 27.5605773925781,
"maxX": -80.0313568115234,
"minX": -81.3108444213867,
"minY": 25.1152248382568
}
},
"extents": [470376],
"permissions": {
"read": {
"acl": ["PUBLIC"],
"inherited": true,
"inheritsFromId": "504108e5e4b07a90c5ec62d4"
},
"write": {
"acl": ["USER:sbristol@usgs.gov"],
"inherited": true,
"inheritsFromId": "4f4f863be4b0c2aeb78a9e3f"
}
}
}
要回答您的第二个问题,如果USGS输出一致的数据并且您的预期json.relationships.links[0].title
可用,那么您应该能够将i
提供的0
参数替换为循环每个都返回relationships.links
而不需要.each()
内的第二个循环(如此)。
$.each(data, function (i, item) {
var link = data.relationships.links[i].url,
title = data.relationships.links[i].title,
a = $('<a />').attr('href', url).text(title),
li = $('<li />').append(a);
$('#sbItems').append(li);
});