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>

运行结果:
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值