AJAX - Ïò·þÎñÆ÷·¢ËÍÇëÇó
XMLHttpRequest ¶ÔÏóÓÃÓںͷþÎñÆ÷½»»»Êý¾Ý¡£
Ïò·þÎñÆ÷·¢ËÍÇëÇó
ÈçÐ轫ÇëÇó·¢Ë͵½·þÎñÆ÷£¬ÎÒÃÇʹÓà XMLHttpRequest ¶ÔÏóµÄ open() ºÍ send() ·½·¨£º
xmlhttp.open("GET","test1.txt",true); xmlhttp.send();
·½·¨ | ÃèÊö |
---|---|
open(method,url,async) |
¹æ¶¨ÇëÇóµÄÀàÐÍ¡¢URL ÒÔ¼°ÊÇ·ñÒì²½´¦ÀíÇëÇó¡£
|
send(string) |
½«ÇëÇó·¢Ë͵½·þÎñÆ÷¡£
|
GET »¹ÊÇ POST£¿
Óë POST Ïà±È£¬GET ¸ü¼òµ¥Ò²¸ü¿ì£¬²¢ÇÒÔڴ󲿷ÖÇé¿ö϶¼ÄÜÓá£
È»¶ø£¬ÔÚÒÔÏÂÇé¿öÖУ¬ÇëʹÓà POST ÇëÇó£º
- ÎÞ·¨Ê¹Óûº´æÎļþ£¨¸üзþÎñÆ÷ÉϵÄÎļþ»òÊý¾Ý¿â£©
- Ïò·þÎñÆ÷·¢ËÍ´óÁ¿Êý¾Ý£¨POST ûÓÐÊý¾ÝÁ¿ÏÞÖÆ£©
- ·¢ËͰüº¬Î´Öª×Ö·ûµÄÓû§ÊäÈëʱ£¬POST ±È GET ¸üÎȶ¨Ò²¸ü¿É¿¿
GET ÇëÇó
Ò»¸ö¼òµ¥µÄ GET ÇëÇó£º
xmlhttp.open("GET","demo_get.asp",true); xmlhttp.send();
ÔÚÉÏÃæµÄÀý×ÓÖУ¬Äú¿ÉÄܵõ½µÄÊÇ»º´æµÄ½á¹û¡£
ΪÁ˱ÜÃâÕâÖÖÇé¿ö£¬ÇëÏò URL Ìí¼ÓÒ»¸öΨһµÄ ID£º
xmlhttp.open("GET","demo_get.asp?t=" + Math.random()
,true);
xmlhttp.send();
Èç¹ûÄúÏ£Íûͨ¹ý GET ·½·¨·¢ËÍÐÅÏ¢£¬ÇëÏò URL Ìí¼ÓÐÅÏ¢£º
xmlhttp.open("GET","demo_get2.asp?fname=Bill&lname=Gates",true); xmlhttp.send();
POST ÇëÇó
Ò»¸ö¼òµ¥ POST ÇëÇó£º
xmlhttp.open("POST","demo_post.asp",true); xmlhttp.send();
Èç¹ûÐèÒªÏñ HTML ±íµ¥ÄÇÑù POST Êý¾Ý£¬ÇëʹÓà setRequestHeader() À´Ìí¼Ó HTTP Í·¡£È»ºóÔÚ send() ·½·¨Öй涨ÄúÏ£Íû·¢Ë͵ÄÊý¾Ý£º
xmlhttp.open("POST","ajax_test.asp",true); xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xmlhttp.send("fname=Bill&lname=Gates");
·½·¨ | ÃèÊö |
---|---|
setRequestHeader(header,value) |
ÏòÇëÇóÌí¼Ó HTTP Í·¡£
|
url - ·þÎñÆ÷ÉϵÄÎļþ
open() ·½·¨µÄ url ²ÎÊýÊÇ·þÎñÆ÷ÉÏÎļþµÄµØÖ·£º
xmlhttp.open("GET","ajax_test.asp",true);
¸ÃÎļþ¿ÉÒÔÊÇÈκÎÀàÐ͵ÄÎļþ£¬±ÈÈç .txt ºÍ .xml£¬»òÕß·þÎñÆ÷½Å±¾Îļþ£¬±ÈÈç .asp ºÍ .php £¨ÔÚ´«»ØÏìӦ֮ǰ£¬Äܹ»ÔÚ·þÎñÆ÷ÉÏÖ´ÐÐÈÎÎñ£©¡£
Òì²½ - True »ò False£¿
AJAX Ö¸µÄÊÇÒì²½ JavaScript ºÍ XML£¨Asynchronous JavaScript and XML£©¡£
XMLHttpRequest ¶ÔÏóÈç¹ûÒªÓÃÓÚ AJAX µÄ»°£¬Æä open() ·½·¨µÄ async ²ÎÊý±ØÐëÉèÖÃΪ true£º
xmlhttp.open("GET","ajax_test.asp",true
);
¶ÔÓÚ web ¿ª·¢ÈËÔ±À´Ëµ£¬·¢ËÍÒì²½ÇëÇóÊÇÒ»¸ö¾Þ´óµÄ½ø²½¡£ºÜ¶àÔÚ·þÎñÆ÷Ö´ÐеÄÈÎÎñ¶¼Ï൱·Ñʱ¡£AJAX ³öÏÖ֮ǰ£¬Õâ¿ÉÄÜ»áÒýÆðÓ¦ÓóÌÐò¹ÒÆð»òÍ£Ö¹¡£
ͨ¹ý AJAX£¬JavaScript ÎÞÐèµÈ´ý·þÎñÆ÷µÄÏìÓ¦£¬¶øÊÇ£º
- Ôڵȴý·þÎñÆ÷ÏìӦʱִÐÐÆäËû½Å±¾
- µ±ÏìÓ¦¾ÍÐ÷ºó¶ÔÏìÓ¦½øÐд¦Àí
Async = true
µ±Ê¹Óà async=true ʱ£¬Çë¹æ¶¨ÔÚÏìÓ¦´¦ÓÚ onreadystatechange ʼþÖеľÍÐ÷״̬ʱִÐеĺ¯Êý£º
xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("myDiv").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","test1.txt",true); xmlhttp.send();
Äú½«ÔÚÉÔºóµÄÕ½Úѧϰ¸ü¶àÓÐ¹Ø onreadystatechange µÄÄÚÈÝ¡£
Async = false
ÈçÐèʹÓà async=false£¬Ç뽫 open() ·½·¨ÖеĵÚÈý¸ö²ÎÊý¸ÄΪ false£º
xmlhttp.open("GET","test1.txt",false);
ÎÒÃDz»ÍƼöʹÓà async=false£¬µ«ÊǶÔÓÚһЩСÐ͵ÄÇëÇó£¬Ò²ÊÇ¿ÉÒԵġ£
Çë¼Çס£¬JavaScript »áµÈµ½·þÎñÆ÷ÏìÓ¦¾ÍÐ÷²Å¼ÌÐøÖ´ÐС£Èç¹û·þÎñÆ÷·±Ã¦»ò»ºÂý£¬Ó¦ÓóÌÐò»á¹ÒÆð»òÍ£Ö¹¡£
×¢ÊÍ£ºµ±ÄúʹÓà async=false ʱ£¬Çë²»Òª±àд onreadystatechange º¯Êý - °Ñ´úÂë·Åµ½ send() Óï¾äºóÃæ¼´¿É£º
xmlhttp.open("GET","test1.txt",false); xmlhttp.send(); document.getElementById("myDiv").innerHTML=xmlhttp.responseText;