<Ajax> 四. get请求(验证用户名是否存在)

<!DOCTYPE html>
<!-- 前端代码 -->
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <input type="text" placeholder="输入一个昵称" id="name"><br>
    <!-- <input type="submit" value="发送请求" id="submit"> -->
<h3></h3>
</body>
</html>

<script src='jquery-3.2.1.js'></script>

<script>
$(function () {
    $("#name").blur(function() {
        // 创建请求对象
        var xhr = new XMLHttpRequest();

        // 请求行
        // 获取参数
        var name = $("#name").val();
        console.log(name);
        
        xhr.open('get', 'getData.php?name=' + name);

        // 请求头
        // xhr.setRequestHeader('a', 'b');

        // 请求体
        xhr.send(null);

        // 注册回调函数
        xhr.onload = function() {
            // xhr.responseText 为服务器返回的数据
            $("h3").text(xhr.responseText);
        };
    });
});
</script>
<?php
    // 后端代码
    // 获取传过来的数据
    $name = $_GET['name'];

    // 用户名数据库
    $nameArr = array("ray", "lee", "918");

    // 查找该用户名是否存在数据库
    $res =  in_array($name, $nameArr);

    // 根据查询结果, 返回数据
    if ($res) {
        echo "已经被注册, 请更换一个!";
    } else {
        echo "没有被使用, 赶快注册吧!";
    }
?>
原文地址:https://www.cnblogs.com/ZeroHour/p/8339939.html