站內搜尋

Tuesday, April 24, 2012

[jQuery] 透過ajax取xml的資料

假如我們要透過index.php使用ajax去抓1.xml的資料,並將資料放到mydiv這個div中顯示出來,程式碼如下...

index.php的程式碼:
<?php
$html=<<<asdf
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$.ajax({
url:"1.xml",
cache:false,
dataType:"xml",
success:function(xml){
$(xml).find("feed").each(function(){
$(this).find("title").each(function(){
var str=$(this).text();
str=str+"<br />";
$("#mydiv").append(str);
});
$(this).find("id").each(function(){
var str1=$(this).text();
str1=str1+"<br />";
$("#mydiv").append(str1);
});
});
}
});
});
</script>
    </head>
    <body>
<div id="mydiv">
</div>
    </body>
</html>
asdf;
echo $html;
?>

說明:這邊使用兩層的迴圈,在每層迴圈中使用this去抓值,要注意的是,必須接.text()可以做字串處理,不然會有錯誤。

如果想要取外網域的xml檔,則可以透過php檔去取,例如1.php:

<?php
if(@file_get_contents("http://www.plurk.com/user/s861175.xml")){
echo file_get_contents("http://www.plurk.com/user/s861175.xml");
}
?>

當然index.php的url:"1.xml",就要改成url:"1.php",

No comments:

Post a Comment