【发布时间】:2012-04-16 15:43:50
【问题描述】:
我正在做的是读取一个 XML 文件并通过 jQuery 将数据获取到我的 HTML 文件中。
正如我在许多教程中发现的那样,我使用的是 jQuery 的 .get() 方法。除了一个问题,它对我很有帮助!
这是 XML 文件:
<?xml version="1.0" encoding="utf-8" ?>
<books>
<book title="CSS Mastery" imageurl="images/css.jpg">
<description>
info goes here.
</description>
</book>
<book title="Professional ASP.NET" imageurl="images/asp.jpg">
<description>
info goes here.
</description>
</book>
<book title="Learning jQuery" imageurl="images/lj.jpg">
<description>
info goes here.
</description>
</book>
</books>
这是我的带有 jQuery 代码的 HTML 文件:
<!doctype html>
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" >
$("document").ready(function() {
$.get("one.xml", function(d) {
var title = [];
var description = [];
$(d).find("book").each(function() {
title.push($(this).attr("title"));
description.push($(this).find("description").text());
});
console.log(title);
});
});
</script>
</head>
<body>
// BODY contents...
</body>
</html>
我想要做的是返回标题和描述,以便我可以在其他函数中使用这些数组。根据jQuery代码,我的title数组现在正在console中打印,但是当我尝试在.get()方法之外打印title数组时,它会显示"title is undefined"。
我尝试在函数末尾返回数组,但没有成功。我不确定我的问题是否清楚,所以我粘贴了下面给出错误的代码:
<!doctype html>
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$("document").ready(function() {
$.get("one.xml", function(d){
var title = [];
var description = [];
$(d).find("book").each(function() {
title.push($(this).attr("title"));
description.push($(this).find("description").text());
});
});
console.log(title);
});
</script>
</head>
<body>
// BODY contents...
</body>
</html>
在这段代码中,它是 "title isn't defined,注意我在 .get() 方法之外对 title 数组进行了调整。
【问题讨论】:
标签: javascript xml jquery xml-parsing scope