text AJAX速成班(香草JS) - TraversyMedia

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了text AJAX速成班(香草JS) - TraversyMedia相关的知识,希望对你有一定的参考价值。

<!DOCTYPE html>
<html lang="en">
	
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Ajax 1 - Text File</title>
</head>

<body>
	<button id="button">Get Text File</button>
	<br><br>
	<div id="text"></div>
	
	<script>
	// Create event listener
	document.getElementById('button').addEventListener('click', loadText);
	
	function loadText(){
		// Create XHR Object
    	var xhr = new XMLHttpRequest();
    	// OPEN - type, url/file, async
    	xhr.open('GET', 'sample.txt', true);
	
		//OLD WAY OF DOING IT
		//console.log('READYSTATE: ', xhr.readyState);

    	// OPTIONAL - used for loaders (loading icons)
    	xhr.onprogress = function(){
        	console.log('READYSTATE: ', xhr.readyState);
    	}
    	
    	xhr.onload = function(){
        	console.log('READYSTATE: ', xhr.readyState);
        	if(this.status == 200){
        		//console.log(this.responseText);
        		document.getElementById('text').innerHTML = this.responseText;
        	} else if(this.status = 404){
        		document.getElementById('text').innerHTML = 'Not Found';
        	}
    	}

    	xhr.onerror = function(){
        	console.log('Request Error...');
    	}
      
		//OLD WAY OF DOING IT
		// xhr.onreadystatechange = function(){
		//   console.log('READYSTATE: ', xhr.readyState);
		//   if(this.readyState == 4 && this.status == 200){
		//     //console.log(this.responseText);
		//   }
		// }
      
		// readyState Values
		// 0: request not initialized 
		// 1: server connection established
		// 2: request received 
		// 3: processing request 
		// 4: request finished and response is ready
		
		// Sends request
		xhr.send();
    }
		// HTTP Statuses
		// 200: "OK"
		// 403: "Forbidden"
		// 404: "Not Found"
    </script>
</body>
</html>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Inventore beatae vitae nulla itaque, assumenda optio libero maxime perferendis fugit, vel et ad tenetur fuga temporibus. Adipisci laboriosam veritatis eaque atque reiciendis. Modi expedita neque libero fugit adipisci molestiae? Porro harum consequuntur excepturi minima corporis culpa quisquam non at quia quaerat?

以上是关于text AJAX速成班(香草JS) - TraversyMedia的主要内容,如果未能解决你的问题,请参考以下文章

将带有香草 Js 的数组从 Ajax 发送到 Laravel 控制器

text 香草js和jQuery

FineUI速成 标签

javascript 无限卷轴香草JS

javascript 香草JS窗口的宽度和高度

javascript 香草JS的例子