ajax-原理及應用
阿新 • • 發佈:2018-12-05
<body> <input type="button" value="請求" onclick="req();"> </body> <script type="text/javascript"> function req() { // xml 一個物件 var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function(){ //console.log(xhr); if(this.readyState == 4){ alert("請求結束"); alert('內容是:'+this.responseText); } } xhr.open('get', 'ajaxed', true); xhr.send(null); } </script>
總結:
ajax請求的主要流程:
- new一個 XMLHttpRequest物件;
- 監聽瀏覽器請求狀態onreadystatechange。整個請求分為四步,readyState的狀態值分別為:1234。當請求為4的時候,標誌請求完成;
- responseText為請求的返回結果;
- open(’'請求方式, ‘請求url’, true);
- send() 請求傳送。