1:在浏览器中找到当前get请求
代码
JS:
let xhr = new XMLHttpRequest();
xhr.open('get', 'get.php');
xhr.send();
PHP:
<?php
echo "hello";
?>
结果
F12>网络(Network),找到get.php点开
在响应(Response)中可以看到PHP文件的内容
2.往指定文件写入新内容
代码
HTML:
<input type="button" onclick="fn()" value="发送">
<script>
function fn() {
//1 创建对象
let xhr = new XMLHttpRequest();
//2 设置请求
xhr.open('get', 'get.php');
// 3 发送请求
xhr.send();
}
</script>
PHP:
<?php
$str="hello world";
$f=fopen('a.txt','a');//'a'代表访问权限是all
fwrite($f,$str);//fwrite(file,string,length)用于写入文件
?>
结果
点击一次按钮,就往a.txt中写入一行helloworld
3.返回值的接收
代码
HTML:
<button onclick="fn()">Send</button>
<script>
function fn() {
var xhr = new XMLHttpRequest();
xhr.open("GET", "./test.php", true);
xhr.send();
// 设置监听以及接收响应信息(返回值)
xhr.onreadystatechange = function() {
// console.log(xhr.readyState);//2 3 4
if (xhr.readyState == 4 && xhr.status == 200) {
// console.log(xhr.response);//hello
// document.body.innerHTML = xhr.response;
document.body.innerHTML = xhr.responseText;//hello
}
}
}
</script>
PHP:
<?php
echo "hello"
?>
4.检测用户名是否存在
代码
HTML:
<label for="">用户名:</label>
<input type="text" onblur="fn(this)">
<span></span>
<script>
var span = document.querySelector("span");
function fn(that) {
/* 知识点1: 行内绑定且传参 == > this指向节点本身(有直接调用者)*/
// console.log(that);//<input type="text" οnblur="fn(this)">
var val = that.value; //获得input文本框内容
var xhr = new XMLHttpRequest(); //创建请求对象
xhr.open("GET", "./user.php?user=" + val, true); //设置请求,注意get请求的传参格式
xhr.send(); //发送请求
xhr.onreadystatechange = function() { //设置监听以及接收返回值(响应信息)
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr.responseText); //1或2(在user.php中设置)
if (xhr.responseText == 1) {
span.innerHTML = "用户名已存在!";
span.style.color = 'red';
} else if (xhr.responseText == 2) {
span.innerHTML = "注册成功!";
span.style.color = 'green';
}
}
}
}
</script>
或者:
<label for="">用户名:</label>
<input type="text"><span></span>
<br>
<input type="button" value="Send" id="btn">
<script>
var span = document.querySelector("span");
var xhr = new XMLHttpRequest();
document.getElementById("btn").addEventListener("click", () => {
xhr.open("GET", "./user.php?user=" + document.querySelectorAll("input")[0].value, true);
xhr.send();
xhr.onreadystatechange = callback;
});
function callback() {
if (xhr.readyState == 4 && xhr.status === 200) {
// console.log(xhr.response);
if (xhr.responseText == 1) {
span.style.color = 'red';
span.innerHTML = '*用户名已存在!';
}
if (xhr.responseText == 2) {
span.style.color = 'green';
span.innerHTML = '*注册成功!';
}
}
}
</script>
PHP:
<?php
// 知识点2:$_GET可接收get请求的参数
// user是对应xhr.open("GET", "./user.php?user=" + val, true);
$user=$_GET['user'];//注意格式是方括号,不是圆括号
$arr=["张三","李四","王五"];//已存在的用户名
// 知识点3:in_array(元素,数组)元素是否存在数组,返回1或空
// echo in_array($user,$arr);//数组包含次元素时返回1
if(in_array($user,$arr)){
echo 1;
}else{
echo 2;
}
?>
知识点
1. 行内绑定且传参 == > this指向节点本身(有直接调用者)
php:
2.$_GET可以接收GET请求的参数
3.in_array($元素,$数组);//元素是否存在数组,返回1或空