如果你已經嘗試使用Javascript寫Ajax,
相信一定覺得程式碼有夠冗長的,
特別是在Ajax宣告部分,
還要因應各個瀏覽器版本需求將所有例外一一處理掉...
看到著大概就要吐掉一公升的血了...
接下來還要寫一堆有的沒的....
說實在的真的不是很人性化壓....
不過當你看到快頭昏腦脹時,
救星來了!!!
就是jQuery啦!!
想要用ajax?很簡單!!!
只要少少幾行輕鬆ok!!
接下來就來個範例唄~~
ajax.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script src="jquery.js" type="text/javascript" ></script>
<script type="text/javascript" language="javascript">
var i=0;
$(document).ready(initial);
function get_value_for_ajax_POST(){
$.ajax({
type: "POST",
url: "2.php",
data:'name=chihwei',
beforeSend:function(){
$('#res2').html("準備中~~");
},
error:function(xhr,textStatus,errorThrown){
alert("出錯啦!!");
},
success: function(msg){
$('#res2').html(msg);
}
});
}
function get_value_for_ajax_GET(){
$.ajax({
type: "GET",
url: "1.php",
data:'name=chihwei',
beforeSend:function(){
$('#res').html("準備中~~");
},
error:function(xhr,textStatus,errorThrown){
alert("出錯啦!!");
},
success: function(msg){
$('#res').html(msg);
}
});
}
function get_value_for_ajax(){
$.ajax({
url: "3.php",
beforeSend:function(){
$('#res3').html("準備中~~");
},
error:function(xhr,textStatus,errorThrown){
alert("出錯啦!!");
},
success: function(msg){
$('#res3').html(msg);
}
});
}
function initial(){
get_value_for_ajax_POST();
get_value_for_ajax_GET();
get_value_for_ajax();
}
</script>
<title>Ajax</title>
</head>
<body>
<div id="res" ></div>
<div id="res2" ></div>
<div id="res3" ></div>
</body>
</html>
1.php
<?php echo "Hi你用的是GET,你傳來得值是:".$_GET["name"]; ?>
2.php
<?php echo "Hi你用的是POST,你傳來得值是:".$_POST["name"]; ?>
3.php
<? echo "Hi~你是用單純取得頁面資料的方式~~"; ?>
如果你有程式底子的話~~
相信看完以上程式碼,
大概就能了解jQuery ajax的運作方式啦~~ :)

沒有留言:
Write 意見