Ajax簡單教程

Ajax流程圖:
在這裏插入圖片描述

一:GET請求

目錄結構
目錄結構
index.html

<html>
<head>
<meta charset="utf-8">
<title>get請求數據</title>
</head>
<body>

<input type="button" value="get數據" />
<h3></h3>


</body>

</html>

<script>
  //點擊事件
  document.querySelector('input').onclick = function(){
	//1.創建對象
	var xhr = new XMLHttpRequest();
	
	//2. 設置請求行
	xhr.open('get','getData.php?name=Daisy&skill=learn');
	
	//3.設置請求頭(get可以省略)
	
	//3.5註冊回調函數
	xhr.onload = function(){
		//獲取數據
		console.log(xhr.responseText);
		
		//修改頁面dom元素
		document.querySelector('h3').innerHTML = xhr.responseText;
		
	}
	
	//4. 請求主體 ( get請求爲空 , 或者寫 null , post請求數據寫在這裏,如果沒有數據,直接爲空或者null )
	
	xhr.send(null);
	
	
  }

</script>

getData.php:

<?php

print_r($_GET);

sleep(2);

運行界面
get運行界面
案例:檢測用戶名是否存在
思路:
思路
index.html

<html>
<head>
<meta charset="utf-8">
<title>賬戶註冊</title>
</head>
<body>
<h2>用戶註冊</h2>
<input type="text" placeholder= "請輸入用戶名" />
<h3></h3>


</body>

</html>

<script>
  //點擊事件
  document.querySelector('input').onblur = function(){
	//1.創建對象
	var xhr = new XMLHttpRequest();
	
	//2. 設置請求行
	xhr.open('get','checkName.php?name='+this.value);
	
	//3.設置請求頭(get可以省略)
	
	//3.5註冊回調函數
	xhr.onload = function(){
		//獲取數據
		console.log(xhr.responseText);
		
		//修改頁面dom元素
		document.querySelector('h3').innerHTML = xhr.responseText;
		
	}
	
	//4. 請求主體 ( get請求爲空 , 或者寫 null , post請求數據寫在這裏,如果沒有數據,直接爲空或者null )
	
	xhr.send(null);
	
	
  }

</script>

checkName.php

<?php

$name = $_GET['name'];
//假數據
$nameArr = array('jack','rose');
//判斷是否存在
$result = in_array($name , $nameArr);

if( $result ){
	echo "有人註冊了,換一個吧";
}else{
	echo "還沒人註冊,趕快註冊哦";
}

運行結果
在這裏插入圖片描述
在這裏插入圖片描述
二:POST請求

目錄結構:
在這裏插入圖片描述
注意: post請求 1.需要添加請求頭 2.數據添加在send中

index.html

<html>
<head>
<meta charset="utf-8">
<title>post請求數據</title>
</head>
<body>
<h2>post請求數據</h2>
<input type="button" value="post數據" />
<h3></h3>


</body>

</html>

<script>
  //點擊事件
  document.querySelector('input').onclick = function(){
	//1.創建對象
	var xhr = new XMLHttpRequest();
	
	//2. 設置請求行
	xhr.open('post','postData.php');
	
	//3.設置請求頭(get可以省略)
	xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded")
	
	//3.5註冊回調函數
	xhr.onload = function(){
		//獲取數據
		console.log(xhr.responseText);
		
		//修改頁面dom元素
		document.querySelector('h3').innerHTML = xhr.responseText;
		
	}
	
	//4. 請求主體 ( get請求爲空 , 或者寫 null , post請求數據寫在這裏,如果沒有數據,直接爲空或者null )
	//post請求發送數據 寫在send中
	// 格式   key=value&key2=value2
	
	xhr.send('name=Daisy&friend=daisy');
	
	
  }

</script>

運行結果:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章