本文实例讲述了jQuery中get方法用法。分享给大家供大家参考,具体如下:
参数:url,[data],[callback],[type]

案例1
表单代码:
1 2 3 4 5 6 | <form id= "form1" action= "#" >
<p>评论:</p>
<p>姓名: <input type= "text" name= "username" id= "username" /></p>
<p>内容: <textarea name= "content" id= "content" rows= "2" cols= "20" ></textarea></p>
<p><input type= "button" id= "send" value= "提交" /></p>
</form>
|
登录后复制
待处理div代码:
1 2 3 | <div class ='comment'>已有评论:</div>
<div id= "resText" >
</div>
|
登录后复制
jQuery代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | <script type= "text/javascript" >
$( function (){
$( "#send" ).click( function (){
$.get( "get1.php" , {
username : $( "#username" ).val() ,
content : $( "#content" ).val()
}, function (data, textStatus){
$( "#resText" ).html(data);
}
);
})
})
</script>
|
登录后复制
PHP代码:
1 2 3 4 | <?php
header( "Content-Type:text/html; charset=utf-8" );
echo "<div class='comment'><h6>{$_REQUEST['username']}:</h6><p class='para'>{$_REQUEST['content']}</p></div>" ;
?>
|
登录后复制
当用户点击send按钮时,触发click事件,对数据进行处理。主要传入两个参数,一个是用户名,一个是内容。这两个参数被传递到php页面。PHP页面处理完毕后,返回输入数据,get方法处理返回的数据。分析代码,可以看出,这数据,被写入了resText这个div层中。整个过程页面并没有刷新。很安静的处理了数据的传输。
案例2,以xml的格式处理数据
表单代码同上。
待处理div代码同上。
jQuery代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | <script type= "text/javascript" >
$( 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);
});
})
})
</script>
|
登录后复制
PHP代码:
1 2 3 4 5 6 7 8 9 | <?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传递参数是相同的,区别在于回调函数对数据处理的方式的不同。从PHP代码中可以看出数据是以xml的格式传入的。
jQuery处理xml就像处理html一样,可以获取属性的值,也可以获取节点的值,获取这些值之后,就可以进行一定的处理,返回到页面中去。
希望本文所述对大家jQuery程序设计有所帮助。
更多jQuery中get方法用法分析相关文章请关注PHP中文网!