Pages

Subscribe:

Ads 468x60px

Labels

2014年4月16日 星期三

AJAX簡易範例(GET、POST傳送)

做一個小範例,就可以發現ajax的威力無窮阿!

首先要做:
以ajax實現頁面不刷新,從前端將值傳送到後端處理,並且回傳給前端顯示
(先做GET傳值、等等再介紹由POST傳值,兩個程式碼幾乎一樣,只改小地方)

共有三個檔案分別是ajax_index.php(主頁)、ajax_example.js(AJAX的JS檔)、ajax_example.php(AJAX的PHP檔)

ajax_index.php(主頁):








 



以ajax實現頁面不刷新,從前端將值傳送到後端處理,並且回傳給前端顯示

ajax_example.js(AJAX的JS檔):
var http_request=false;
function test_ajax(variable){
 http_request=false;
 if(window.XMLHttpRequest){
  http_request=new XMLHttpRequest();
  if(http_request.overrideMimeType){
   http_request.overrideMimeType('text/xml');
  }
 }else if(window.ActiveXObject){
  try{ //6.0+
   http_request=new ActiveXObject("Msxml2.XMLHTTP");
  }catch(e){
   try{ //5.5+
    http_request=new ActiveXObject("Microsoft.XMLHTTP");
   }catch (e){}
  }
 }
 if(!http_request){
  alert('Giving up :( Cannot create a XMLHTTP instance');
  return false;
 }
 http_request.onreadystatechange=show_area;
 http_request.open('GET','ajax_example.php?variable='+variable,true);
 http_request.send(null);
}

function show_area(){
 if(http_request.readyState==4){
  if(http_request.status==200){
   $('#test').val('');  //將輸入框清空
   $('#show_area').append(http_request.responseText);  //將結果顯示出來
  }
 }
}

ajax_example.php(AJAX的PHP檔):
';  //將傳送進來的字元轉成ascii碼
?>

顯示結果:

就是這麼easy~
如果要傳送多個變數,則改寫成  var1=變數1&var2=變數2  如下:
http_request.open('GET','ajax_example.php?var1='+var1+'&var2='+var2,true);

接下來講以POST傳送
也很簡單! 首先修改ajax_example.js檔
var by_post='variable='+variable; //將變數放進字串
http_request.onreadystatechange=show_area;
http_request.open('POST','ajax_example.php',true);
http_request.setRequestHeader("Content-Type","application/x-www-form-urlencoded;");  //**重要一定要加上
http_request.send(by_post);
修改地方不大
1.首先我們將variable變數寫成類似get傳送變數一樣的寫法並且將字串指定給by_post這個變數

2.將open()那由'get'改成'post',網址只留PHP檔案路徑,問號(?)以後的都刪除,因為我們不是由GET傳送了

3.加上http_request.setRequestHeader("Content-Type","application/x-www-form-urlencoded;");

4.將by_post這個變數傳送到PHP

ajax_example.php:
這裡改的變動不大,由GET改成POST而已

結論:
AJAX應用非常廣泛,如:
檢查會員帳號是否重覆、每秒顯示伺服器時間等等...

沒有留言:

張貼留言