ajax5-ajax错误处理
  TEZNKK3IfmPf 2023年11月14日 28 0

ajax5-ajax错误处理

 ajax.js

// 引用expess框架
const express = require('express');
// 处理路径
const path = require('path');
 
const bodyParser = require('body-parser');
 
 
// 创建网站服务器
const app = express();
app.use(bodyParser.json());
app.get('/first', (req, res) => {
    res.send('hello geyao')
})
app.get('/responsdate', (req, res) => {
    res.send({ "name": "geyao" })
})
app.post('/post', (req, res) => {
    res.send(req.body);
})
app.get('/get', (req, res) => {
    res.send(req.query);
})
app.post('/json', (req, res) => {
    res.send(req.body);
})
app.get('/readystate', (req, res) => {
    res.send('hello');
})
app.get('/error', (req, res) => {
    res.status(400).send('not ok');
})
 
app.use(express.static(path.join(__dirname)));
// 监听端口
app.listen(3000);
console.log('网站服务器启动成功, 请访问localhost')

ajax6.html

<!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 xhr = new XMLHttpRequest();
        xhr.open('get', 'http://localhost:3000/error');
        xhr.onreadystatechange = function() {
 
            //
            if (xhr.readyState == 4) {
                //属性获取状态码
                console.log(xhr.responseText);
                console.log(xhr.status);
                if (xhr.status == 400) {
                    console.log('请求出错');
                } else if (xhr.readyState == 404) {
                    console.log('地址错误');
                }
            }
            xhr.onerror = function() {
                console.log('网络中断,无法发送ajax请求')
            }
        }
        xhr.send();
    </script>
</body>
 
</html>

运行结果

ajax5-ajax错误处理

 

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 2023年11月14日 0

暂无评论

推荐阅读
  TEZNKK3IfmPf   2023年11月14日   18   0   0 ajax前端javascript
  TEZNKK3IfmPf   2024年03月22日   94   0   0 ajaxjavascript
  TEZNKK3IfmPf   2023年11月14日   28   0   0 ajax
  TEZNKK3IfmPf   2023年11月15日   27   0   0 ajaxjs
  TEZNKK3IfmPf   2023年11月14日   20   0   0 ajax前端javascript
  TEZNKK3IfmPf   2023年11月14日   25   0   0 ajaxjQuery
  TEZNKK3IfmPf   2023年11月14日   14   0   0 ajaxjQuery
  TEZNKK3IfmPf   2023年11月14日   19   0   0 ajaxpostjavascript
  TEZNKK3IfmPf   2023年11月14日   27   0   0 ajax
  TEZNKK3IfmPf   19天前   31   0   0 ajaxxml
  TEZNKK3IfmPf   2023年11月14日   36   0   0 ajaxjQuery
TEZNKK3IfmPf