jQuery解析與處理服務器端返回xml格式數(shù)據(jù)的方法詳解
本文實例講述了jQuery解析與處理服務器端返回xml格式數(shù)據(jù)的方法。分享給大家供大家參考,具體如下:
1.php代碼:
<?php header("Content-Type:text/xml; charset=utf-8");//聲明瀏覽器端返回數(shù)據(jù)的格式為xml文檔格式 echo "<?xml version='1.0' encoding='utf-8'?>". "<comments>". "<comment username='{$_REQUEST['username'] }' >". "<content>{$_REQUEST['content']}</content>". "</comment>". "</comments>"; ?>
2.html代碼:
<form id="form1" action="#"> <p>評論:</p> <p>姓名: <input type="text" name="username" id="username" /></p> <p>內(nèi)容: <textarea name="content" id="content" rows="2" cols="20"></textarea></p> <p><input type="button" id="send" value="提交"/></p> </form> <div class='comment'>已有評論:</div> <div id="resText" ></div>
3.jQuery代碼:
<script src="jquery-1.3.1.js" type="text/javascript"></script> <script type="text/javascript"> /* 1.由于服務器端返回的數(shù)據(jù)格式是xml文檔,因此需要對返回的數(shù)據(jù)進行處理,jquery處理xml文檔與處理html文檔一樣,也可以使用常規(guī)的attr()、find()、filter()以及其它方法 2.返回數(shù)據(jù)格式為xml文檔的過程實現(xiàn)起來比html片段要稍微復雜點,但xml文檔的可移植性是其他數(shù)據(jù)格式無法比擬的,因此以這種格式提供的數(shù)據(jù)的重用性將極大提高 3.很多知名網(wǎng)站和開放平臺都是以xml格式輸出數(shù)據(jù),合作者可利用他們提供的API,將獲得的內(nèi)容整合到自己的網(wǎng)站中 4.xml文檔體積相對較大,與其它文件格式相比,解析和操作他們的速度要慢一些 5.由于期待服務器端返回的數(shù)據(jù)格式是xml文檔,因此需要在服務器端設置content-type類型,如: header("content-type:text/xml;charset=utf-8"); */ $(function(){ $("#send").click(function(){ $.get("get2.php", { username : $("#username").val() , content : $("#content").val() }, function (data, textStatus){ //data:xml格式的數(shù)據(jù);從data【xml格式數(shù)據(jù)】中查找comment元素username屬性的值 var username = $(data).find("comment").attr("username");//跟解析html文檔類似 var content = $(data).find("comment content").text(); var txtHtml = "<div class='comment'><h6>"+username+":</h6><p class='para'>"+content+"</p></div>"; $("#resText").html(txtHtml); // 把返回的數(shù)據(jù)添加到頁面上 }); }) }) </script>
更多關(guān)于jQuery相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《jQuery操作xml技巧總結(jié)》、《jQuery擴展技巧總結(jié)》、《jQuery常用插件及用法總結(jié)》、《jQuery拖拽特效與技巧總結(jié)》、《jQuery表格(table)操作技巧匯總》、《jquery中Ajax用法總結(jié)》、《jQuery常見經(jīng)典特效匯總》、《jQuery動畫與特效用法總結(jié)》及《jquery選擇器用法總結(jié)》
希望本文所述對大家jQuery程序設計有所幫助。
相關(guān)文章

JQuery的Validation插件中Remote驗證的中文問題

Raphael一個用于在網(wǎng)頁中繪制矢量圖形的Javascript庫