本文實(shí)例講述了jQuery解析與處理服務(wù)器端返回xml格式數(shù)據(jù)的方法。分享給大家供大家參考,具體如下:
1.php代碼:
<?php header("Content-Type:text/xml; charset=utf-8");//聲明瀏覽器端返回?cái)?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íng)論:</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'>已有評(píng)論:</div><div id="resText" ></div>
3.jQuery代碼:
<script src="jquery-1.3.1.js" type="text/javascript"></script><script type="text/javascript">/*1.由于服務(wù)器端返回的數(shù)據(jù)格式是xml文檔,因此需要對(duì)返回的數(shù)據(jù)進(jìn)行處理,jquery處理xml文檔與處理html文檔一樣,也可以使用常規(guī)的attr()、find()、filter()以及其它方法2.返回?cái)?shù)據(jù)格式為xml文檔的過程實(shí)現(xiàn)起來比html片段要稍微復(fù)雜點(diǎn),但xml文檔的可移植性是其他數(shù)據(jù)格式無法比擬的,因此以這種格式提供的數(shù)據(jù)的重用性將極大提高3.很多知名網(wǎng)站和開放平臺(tái)都是以xml格式輸出數(shù)據(jù),合作者可利用他們提供的API,將獲得的內(nèi)容整合到自己的網(wǎng)站中4.xml文檔體積相對(duì)較大,與其它文件格式相比,解析和操作他們的速度要慢一些5.由于期待服務(wù)器端返回的數(shù)據(jù)格式是xml文檔,因此需要在服務(wù)器端設(shè)置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擴(kuò)展技巧總結(jié)》、《jQuery常用插件及用法總結(jié)》、《jQuery拖拽特效與技巧總結(jié)》、《jQuery表格(table)操作技巧匯總》、《jquery中Ajax用法總結(jié)》、《jQuery常見經(jīng)典特效匯總》、《jQuery動(dòng)畫與特效用法總結(jié)》及《jquery選擇器用法總結(jié)》
希望本文所述對(duì)大家jQuery程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注