ajax 入门 (L01)

110 阅读1分钟
<body>
	<button id="button">请求纯文本</button>
	
    <script>
    	document.getElementById('button').addEventListener('click', loadText);

    	function loadText(){
    		var xhr = new XMLHttpRequest();
    		// type {get, post} url/file{ 地址 } , async {true, false}
    		xhr.open('get', 'sample.txt', true)

            // 两种方式请求  onload / onreadystatechange
            xhr.onload =  function(res){
                console.log(this.responseText)
            }

            xhr.onreadystatechange  = function(){
                xhr.readyState;
                xhr.status;
                console.log(this.responseText)
            }

            xhr.send(); // 发送请求
    	}
    </script>
</body>