ajax的基本使用

10 篇文章 0 订阅

服务器代码

//引入express模块
const express = require('express');
//路径处理模块
const path = require('path');
const bodyParser = require('body-parser');
const fs = require('fs');
//创建服务器
const app = express();
app.use(bodyParser.json());

//静态资源访问服务功能
app.use(express.static(path.join(__dirname, 'public')));
app.get('/first', (req, res) => {
    res.send('hello ajax')
});
app.get('/responseData', (req, res) => {
    res.send({ "name": "张三" });
});
//通过req.query获得地址栏上的
app.get('/get', (req, res) => {
    res.send(req.query);
});
app.post('/post', (req, res) => {
    res.send(req.body)
});
app.post('/json', (req, res) => {
    res.send(req.body)
});
app.get('/readystate', (req, res) => {
    res.send('hello')
});
app.get('/error', (req, res) => {
    // console.log(abc);
    res.status(400).send('not ok')
});
app.get('/cache', (req, res) => {
    fs.readFile('./test.txt', (err, result) => {
        res.send(result);
    })
});
//监听端口
app.listen(3000);
console.log('服务器启动成功');

1.第一次使用ajax

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        //1.创建ajax对象
        // XMLHttpRequest
        var xhr = new XMLHttpRequest();

        //2.告诉ajax对象要向哪发送请求   以什么方式发送请求
        //1)请求方式  2)请求地址
        xhr.open('get', 'http://localhost:3000/first');
        //3.发送请求
        xhr.send();
        //4.获取服务器端响应到客户端的数据
        xhr.onload = function() {
            // xhr.responseText  保存的是服务器发给浏览器的数据
            console.log(xhr.responseText);
        }
    </script>
</body>

</html>

2.处理服务器返回的JSON数据

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        //创建ajax对象
        var xhr = new XMLHttpRequest();
        //告诉ajax对象要向哪儿发送请求  以什么方式发送请求
        //1)请求方法2)请求的地址
        xhr.open('get', 'http://localhost:3000/responseData');
        //发送请求
        xhr.send();
        //获取服务器端响应的客户端数据
        xhr.onload = function() {
            console.log(xhr.responseText);
            console.log(typeof xhr.responseText);
            var responseText = JSON.parse(xhr.responseText);
            console.log(responseText);
            var str = "<h2>" + responseText.name + "</h2>"
            document.body.innerHTML = str;
        }
    </script>
</body>

</html>

3.传递get请求参数

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <p>
        <input type="text" name="" id="username">
    </p>
    <p>
        <input type="text" name="" id="age">
    </p>
    <p>
        <input type="button" value="提交" id="btn">
    </p>
    <script>
        var btn = document.querySelector('#btn');
        var username = document.querySelector("#username");
        var age = document.querySelector("#age");
        btn.onclick = function() {
            //创建ajax对象
            var xhr = new XMLHttpRequest();
            var nameValue = username.value;
            var ageValue = age.value;
            // console.log(nameValue);
            // console.log(ageValue);
            //配置ajax对象
            //username=123&age=456
            //拼接请求参数
            var params = 'username=' + nameValue + '&age=' + ageValue;
            //get请求参数要跟在请求地址的后面
            xhr.open("get", "http://localhost:3000/get?" + params);
            //发送请求
            xhr.send();
            //获取服务器端响应的数据
            xhr.onload = function() {
                console.log(xhr.responseText);
            }
        }
    </script>
</body>
</html>

4.传递post请求参数

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <p>
        <input type="text" name="" id="username">
    </p>
    <p>
        <input type="text" name="" id="age">
    </p>
    <p>
        <input type="button" value="提交" id="btn">
    </p>
    <script>
        var btn = document.querySelector('#btn');
        var username = document.querySelector("#username");
        var age = document.querySelector("#age");
        btn.onclick = function() {
            //创建ajax对象
            var xhr = new XMLHttpRequest();
            var nameValue = username.value;
            var ageValue = age.value;
            console.log(nameValue);
            console.log(ageValue);

            //拼接请求参数
            var params = 'username=' + nameValue + '&age=' + ageValue;
            //配置ajax对象
            xhr.open('post', 'http://localhost:3000/post');
            //设置请求头信息  设置请求参数格式的类型 (post请求必须要设置)   字符串形式的参数  用这种类型 
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            //发送请求
            xhr.send(params);
            //获取服务器端响应的数据
            xhr.onload = function() {
                console.log(xhr.responseText);
            }
        }
    </script>
</body>
</html>

5.向服务器传递JSON类型的参数

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        //创建ajax对象
        var xhr = new XMLHttpRequest();
        //配置ajax对象
        xhr.open('post', 'http://localhost:3000/json');
        //设置请求头信息  设置请求参数格式的类型 (post请求必须要设置)
        xhr.setRequestHeader('Content-Type', 'application/json');
        //发送请求  传递参数必须以字符串的形式传递  所以  必须用JSON.stringify转化为字符串
        xhr.send(JSON.stringify({
            name: 'list',
            age: 50
        }));
        //获取服务器端响应的数据
        xhr.onload = function() {
            console.log(xhr.responseText);
        }
    </script>
</body>

</html>

6.获取服务器端响应数据的另一种方式

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>

    <script>
        var xhr = new XMLHttpRequest();
        //0已经创建了ajax对象  但是还没有对ajax对象进行配置
        console.log(xhr.readyState);
        xhr.open('get', 'http://localhost:3000/readystate');
        //1 已经对ajax对象进行配置  但是还没有发生请求
        console.log(xhr.readyState);
        //当ajax状态码发生变化时触发
        xhr.onreadystatechange = function() {
            //2请求已经发送了
            //3已经接受到服务器端的部分数据了
            //4服务器端的响应数据已经接受完成
            //对ajax状态码进行判断
            //如果状态码的值为4  就代表数据已经接受完成了
            console.log(xhr.readyState);
            if (xhr.readyState == 4) {
                console.log(xhr.responseText);
            }
        }
        xhr.send();
    </script>
</body>

</html>

7.Ajax错误处理

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <button id="btn">发送ajax请求</button>
    <script>
        var btn = document.querySelector('#btn')
        btn.onclick = function() {
            //创建ajax对象
            var xhr = new XMLHttpRequest();
            //配置ajax对象
            xhr.open('get', 'http://localhost:3000/error');
            //发送请求
            xhr.send();
            //获取响应的数据
            xhr.onload = function() {
                //xhr.status  获取http状态码
                console.log(xhr.responseText);
                if (xhr.status == 400) {
                    console.log('请求出错');
                };
            }
            xhr.onerror = function() {
                alert('网络中断无法发送ajax请求')
            }
        };
        //Ajax状态码  表示ajax请求的过程状态  ajax对象返回的
        //http状态码  表示请求的处理结果  是服务器端返回的
    </script>
</body>

</html>

8.ajax缓存

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <button id="btn">发送ajax请求</button>
    <script>
        var btn = document.querySelector('#btn')
        btn.onclick = function() {
            //创建ajax对象
            var xhr = new XMLHttpRequest();
            //配置ajax对象   //给后面加上随机数   IE低版本浏览器就不会认为是一个地址  IE低版本浏览器认为是同一个地址就不会更新数据
            xhr.open('get', 'http://localhost:3000/cache?t' + Math.random());
            //发送请求
            xhr.send();
            //获取响应的数据
            xhr.onreadystatechange = function() {
                // console.log(1);
                if (xhr.readyState == 4 && xhr.status == 200) {
                    alert(xhr.responseText)
                }
            }
        };
        //Ajax状态码  表示ajax请求的过程状态  ajax对象返回的
        //http状态码  表示请求的处理结果  是服务器端返回的
    </script>
</body>

</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值