本文實(shí)例講述了jQuery中g(shù)et方法用法。分享給大家供大家參考,具體如下:
參數(shù):url,[data],[callback],[type]
url 待載入頁(yè)面的URL地址。 data 待發(fā)送 Key/value 參數(shù)。 callback 載入成功時(shí)回調(diào)函數(shù)。 type 返回內(nèi)容格式,xml, html, script, json, text, _default。
案例1
表單代碼:
<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代碼:
<div class='comment'>已有評(píng)論:</div> <div id="resText" > </div>
jQuery代碼:
<script type="text/javascript"> //<![CDATA[ $(function(){ $("#send").click(function(){ $.get("get1.php", { username : $("#username").val() , //傳入?yún)?shù) content : $("#content").val() }, function (data, textStatus){ $("#resText").html(data); // 把返回的數(shù)據(jù)添加到頁(yè)面上 } ); }) }) //]]> </script>
PHP代碼:
<?php header("Content-Type:text/html; charset=utf-8"); echo "<div class='comment'><h6>{$_REQUEST['username']}:</h6><p class='para'>{$_REQUEST['content']}</p></div>"; ?>
當(dāng)用戶(hù)點(diǎn)擊send按鈕時(shí),觸發(fā)click事件,對(duì)數(shù)據(jù)進(jìn)行處理。主要傳入兩個(gè)參數(shù),一個(gè)是用戶(hù)名,一個(gè)是內(nèi)容。這兩個(gè)參數(shù)被傳遞到php頁(yè)面。PHP頁(yè)面處理完畢后,返回輸入數(shù)據(jù),get方法處理返回的數(shù)據(jù)。分析代碼,可以看出,這數(shù)據(jù),被寫(xiě)入了resText這個(gè)div層中。整個(gè)過(guò)程頁(yè)面并沒(méi)有刷新。很安靜的處理了數(shù)據(jù)的傳輸。
案例2,以xml的格式處理數(shù)據(jù)
表單代碼同上。
待處理div代碼同上。
jQuery代碼:
<script type="text/javascript"> //<![CDATA[ $(function(){ $("#send").click(function(){ $.get("get2.php", { username : $("#username").val() , content : $("#content").val() }, function (data, textStatus){ var username = $(data).find("comment").attr("username"); 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ù)添加到頁(yè)面上 }); }) }) //]]> </script>
PHP代碼:
<?php header("Content-Type:text/xml; charset=utf-8"); echo "<?xml version='1.0' encoding='utf-8'?>". "<comments>". "<comment username='{$_REQUEST['username'] }' >". "<content>{$_REQUEST['content']}</content>". "</comment>". "</comments>"; ?>
jQuery傳遞參數(shù)是相同的,區(qū)別在于回調(diào)函數(shù)對(duì)數(shù)據(jù)處理的方式的不同。從PHP代碼中可以看出數(shù)據(jù)是以xml的格式傳入的。
jQuery處理xml就像處理html一樣,可以獲取屬性的值,也可以獲取節(jié)點(diǎn)的值,獲取這些值之后,就可以進(jìn)行一定的處理,返回到頁(yè)面中去。
更多關(guān)于jQuery相關(guān)內(nèi)容感興趣的讀者可查看本站專(zhuān)題:《jquery中Ajax用法總結(jié)》、《jQuery form操作技巧匯總》、《jQuery常用插件及用法總結(jié)》、《jQuery操作json數(shù)據(jù)技巧匯總》、《jQuery擴(kuò)展技巧總結(jié)》、《jQuery拖拽特效與技巧總結(jié)》、《jQuery表格(table)操作技巧匯總》、《jQuery常見(jiàn)經(jīng)典特效匯總》、《jQuery動(dòng)畫(huà)與特效用法總結(jié)》及《jquery選擇器用法總結(jié)》
希望本文所述對(duì)大家jQuery程序設(shè)計(jì)有所幫助。