$.ajax()——超时设置,增加 loading 提升体验
前端发送Ajax请求到服务器,服务器返回数据这一过程,因原因不同耗时长短也有差别,且这段时间内页面显示空白。如何优化这段时间内的交互体验,以及长时间内服务器仍未返回数据这一问题,是我们开发中不容忽视的重点。
常见的做法是:
1、设置超时时间,一旦时间超过设定值,便终止请求;
2、页面内容加载之前,手动增加一个 loading 层。
代码如下:
getAjax: function (method, apiUrl, options, callback) {
var xhr = $.ajax({
type: method,
url: apiUrl,
data: options,
timeout: 5000, // 设置超时时间
dataType: "json",
beforeSend: function (xhr) {
$.showLoading(); // 数据加载成功之前,使用loading组件
},
success: function(json) {
$.hideLoading(); // 成功后,隐藏loading组件
if(callback && callback instanceof Function === "true") {
callback(json);
}
},
error: function (textStatus) {
console.error(textStatus);
},
complete: function (XMLHttpRequest,status) {
if(status == 'timeout') {
xhr.abort(); // 超时后中断请求
$.alert("网络超时,请刷新", function () {
location.reload();
})
}
}
})
}
随机推荐
- Spring集成Mybatis配置文件的简单理解
详情可见官方文档http://www.mybatis.org/spring/zh/index.html 一.需要配置的对象实例 1.SqlSessionFactoryBean 在 MyBatis-Sp ...
- iOS正确解决隐藏导航栏后push和pop或dismiss和present闪黑问题
情景: 一级页面不显示导航栏 ,二级页面显示导航栏. 方法一 适用于push/pop: 一级页面中 - (void)viewWillAppear:(BOOL)animated { [super vie ...
- [leetcode]134. Gas Station加油站
There are N gas stations along a circular route, where the amount of gas at station i is gas[i]. Y ...
- Visual Studio工具 vcpkg简介
博客参考: https://blog.csdn.net/cjmqas/article/details/79282847#43-%E7%A7%BB%E9%99%A4%E5%85%A8%E5%B1%80% ...
- Golang之json序列化(struct,int,map,slice)
老规矩,直接上代码 package main import ( "encoding/json" "fmt" ) //把结构体都改小写 type User str ...
- Windows c++程序的基本结构
Windows c++程序的基本结构 1.一个完整的Windows应用程序通常由五种类型的文件组成 C语言源程序文件 头文件 模块定义文件 资源描述文件 项目文件 2.Windows应用程序构成基本框 ...
- 静态HTML服务器
主要代码 #pragma once#include "pre.h"#include <thread> NAMESPACE(DEF) class Socket {publ ...
- 16 Finding a Protein Motif
Problem To allow for the presence of its varying forms, a protein motif is represented by a shorthan ...
- 【笔记】metasploit渗透测试魔鬼训练营-信息搜集
exploit 漏洞利用代码 编码器模块:免杀.控制 help [cmd] msfcli适合对网络中大量系统统一测试. 打开数据包路由转发功能:/etc/sysctl.conf /etc/rc.loc ...
- Linux 基础教程 41-系统关机和重启
在Linux系统中,仅仅是关机和重启相关的命令就至少有5个,shutdown. halt.poweroff.reboot.init.各个命令作用如下所示: 命令 说明 shutdown 可用于 ...