[JavaSript] 原生JS实现 Ajax


原生JS实现 Ajax

1. 运行服务器

  • 之前是用 txt 文件模拟的 AJAX 服务器, 现在用 jar 包模拟原生 JS 的 AJAX 服务器。文件下载地址:https://download.csdn.net/download/Regino/12322211
  • 打开 CMD,在安装目录下运行 java -jar ajax_server.jar
    在这里插入图片描述
  • 输入地址:http://localhost:8080/check?username=123 测试一下服务器:
    在这里插入图片描述

2. 案例需求

在这里插入图片描述


3. 相关语法

1. 创建ajax对象
		let xhr = new XMLHttpRequest();

2. 告诉ajax请求方式和请求地址
		xhr.open(请求方式,请求地址);

3. 发送请求
		xhr.send();

4. 获取服务器返回的数据
		xhr.onload=function(){
            xhr.responseText;
		}

4. 代码实现

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>原生js实现ajax</title>
    <style>
        span{
            color: red;
        }
    </style>
</head>
<body>
<input id="username" type="text" placeholder="请输入用户名"><span id="userwarn"></span>
<script>
    document.getElementById('username').onblur=function () {
        console.log(this.value);
        // 1.创建ajax对象
        let xhr = new XMLHttpRequest();
        // 2.告诉ajax请求方式和请求地址
        xhr.open('get','http://localhost:8080/check?username='+this.value)
        // 3.发送请求
        xhr.send();
        // 4.获取服务器返回数据
        xhr.onload=function () {
            console.log(xhr.responseText);// 返回的字符串
            document.getElementById('userwarn').innerText=xhr.responseText;
        }
    }
</script>
</body>
</html>
  • 效果图:
    在这里插入图片描述
    在这里插入图片描述
    在这里插入图片描述

原文链接:https://qwert.blog.csdn.net/article/details/105456834

发布了369 篇原创文章 · 获赞 381 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/Regino/article/details/105456834