我正在尝试使用getJSON和YQL解析YAHOO数据
连接运行良好,我检索我可以看到的数据并登录到控制台,但我无法将数据打印到我正在使用的JSP页面中。我用过这里接受的答案:
http://jsbin.com/umuri5/1/edit
收效甚微。这是我的JSP:
<%@page import="p.build.classes.p.*"%>
<!DOCTYPE JSP>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>untitled</title>
<style type="text/css">
body { text-align: center; }
</style>
</head>
<body onLoad="gova();">
<div id="container">
</div>
<table id="userdata" border="1">
<thead>
<th>Change</th>
</thead>
<tbody></tbody>
</table>
<script id="userTemplate" type="text/x-jquery-tmpl">
<tr>
<td>${Change}</td>
</tr>
</script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<script src="https://raw.github.com/jquery/jquery-tmpl/master/jquery.tmpl.min.js" type="text/javascript" charset="utf-8"></script>
<script src="scripts/script.js"></script>
<script type="text/javascript">
function gova() {
requestCrossDomainJSON(
'yahoo.finance.quote',
function(results) {
var i, t = $('#userTemplate'), tbody = $('#userdata tbody');
// console.log(data.query.results);
for (var i = 0; i < results.userdata.length; i++) {
t.tmpl(results.userdata[i]).appendTo(tbody);
}
}
);
return false;
}
</script>
</body>
</html>
这是我的脚本script.js:
function requestCrossDomainJSON( site, callback ) {
if ( !site ) {
alert('No site was passed.');
return false;
}
var yql = 'http://query.yahooapis.com/v1/public/yql?q=select%20Change%20from%20' + site + '%20where%20symbol%20in%20(%22YHOO%22)&format=json&diagnostics=true&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&callback=?';
// Request that YSQL string, and run a callback function.
// Pass a defined function to prevent cache-busting.
function cbfunc(data) {
console.log(data);
// If we have something to work with...
if ( ! data.error && data.query.results) {
// If the user passed a callback, and it
// is a function, call it, and send through the data var.
if ( typeof callback === 'function') {
callback(data.query.results.json);
}
}
// Else, Maybe we requested a site that doesn't exist, and nothing returned.
else throw new Error('Nothing returned from getJSON.');
}
// Request that YQL string, and run a callback function.
// Pass a defined function to prevent cache-busting.
$.getJSON( yql, cbfunc );
// console.log(data.query.results);
};
错误发生在以下行:
for (var i = 0; i < results.userdata.length; i++) {
t.tmpl(results.userdata[i]).appendTo(tbody);
}
控制台说它无法读取未定义的属性userdata。因为JQuery模板被折旧了,我应该使用更好的方法将这些数据放到我的页面中吗?如果这仍然是我遇到的问题的有效解决方案,如果它在未定义的情况下我应如何引用被调用的JSON的结果功能提供。我也试过用HTML文件代替JSP。
提前谢谢。
答案 0 :(得分:1)
来自the URL you're making the request to的回复的results
部分返回:
results: {
quote: {
Change: "-0.061"
}
}
你期待这个吗?
如果是这样,您需要抓取data.query.results['quote']['Change']
或data.query.results.quote.Change
,而不是尝试将data.query.results.json
传递给回调,然后查看results.userdata