jq--ajax中止请求

比如我后端设置延迟3s再响应给前端,我用的是node之koa2

router.get('/vueDemo/getStudents', async ( ctx ) => {
    //延迟3s
    async function delay(time) {
        return new Promise(function(resolve, reject) {
            setTimeout(function(){
                resolve();
            }, time);
        });
    };
    await delay(3000);

    //向后断返回数据
    let st = await students.find();
    ctx.response.type = 'application/json';
    ctx.body = st;
})

前端设置超时

<script>
        var url='http://localhost:3000/vueDemo/getStudents'
        //发起请求
        var getStudents=$.ajax({
            type: 'get',
            url:url,
            timeout:2000
        })
        getStudents.then(function (rep) {
            console.log(rep)
        },function () {
            //如果超过2s还未回应,中断请求
            console.log('超过2s还未回应,中断请求')
            getStudents.abort()
        })
</script>

前端设置非超时

<script>
        var url='http://localhost:3000/vueDemo/getStudents'
        //发起请求
        var getStudents=$.ajax({
            type: 'get',
            url:url,
            timeout:5000
        })
        getStudents.then(function (rep) {
            console.log(rep)
        },function () {
            //如果超过2s还未回应,中断请求
            console.log('超过2s还未回应,中断请求')
            getStudents.abort()
        })
</script>

原文地址:https://www.cnblogs.com/dshvv/p/7784415.html