我在做的是讀取一個XML文件,並通過jQuery將數據導入到我的HTML文件中。返回通過jQuery解析的XML數據
正如我在許多教程中發現的,我使用的是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>
這是我的HTML文件使用jQuery代碼:
<!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
並注意我安慰了title
陣列在.get()
方法之外。
我曾經想過這個,但我只是好奇,如果有任何其他方式。我相當新的jquery反正我感謝你的幫助!豎起大拇指! – 2012-04-16 16:50:16
@FoysalAhmed - 我瞭解你對jQuery的好奇心,但我總是喜歡你搜索已經問過的問題,如果你沒有找到你的問題的答案,然後創建新的問題......無論如何,祝你好運! – 2012-04-16 16:53:38
我已經通過谷歌和stackoverflow搜索,但我沒有找到任何人以這種方式使用它。我所見過的大部分教程和解決方案都是關於從文檔中的xml文件打印接收到的數據。這就是爲什麼我不得不發佈這個問題。我認爲可能有一些方法可以獲得在函數外部返回的數據。 – 2012-04-16 16:59:59