illustrate
xhr.timeout = 2000
Set the timeout via
xhr.ontimeout = function(){...}
Set the timeout method by
By xhr.onerror = function(){...}
setting network connection errors, setting offline work in the network options can simulate a disconnected environment.
Front-end page
< html>
< head>
< meta http-equiv = " Access-Control-Allow-Origin" content = " *" />
</ head>
< body>
< button> press</ button>
< div id = " content" style = " width : 300px; height : 200px; border : 1px solid; " > </ div>
</ body>
< script>
const btn = document. getElementsByTagName ( 'button' ) [ 0 ] ;
const content = document. getElementById ( 'content' ) ;
btn. onclick = function ( ) {
const xhr = new XMLHttpRequest ( ) ;
xhr. timeout = 2000
xhr. ontimeout = function ( ) {
alert ( "网络3秒内无法连接" )
}
xhr. onerror = function ( ) {
alert ( "网络出现问题" )
}
xhr. open ( 'GET' , 'http://127.0.0.1:8000/delay' ) ;
xhr. send ( 'a=200&b=300' ) ;
xhr. onreadystatechange = function ( ) {
if ( xhr. readyState === 4 ) {
if ( xhr. status >= 200 && xhr. status < 300 ) {
console. log ( xhr. status) ;
console. log ( xhr. statusText) ;
console. log ( xhr. getAllResponseHeaders ( ) ) ;
console. log ( xhr. response) ;
content. innerHTML = xhr. response;
}
}
}
}
</ script>
</ html>
backend script
const express = require ( 'express' ) ;
const app = express ( )
app. get ( '/server' , ( Request, Response ) => {
Response. setHeader ( 'Access-Control-Allow-Origin' , '*' )
Response. send ( 'Hello Ajax' )
} )
app. get ( '/delay' , ( Request, Response ) => {
Response. setHeader ( 'Access-Control-Allow-Origin' , '*' )
setTimeout ( ( ) => {
Response. send ( 'Hello Ajax' )
} , 3000 )
} )
app. get ( '/ie' , ( Request, Response ) => {
Response. setHeader ( 'Access-Control-Allow-Origin' , '*' )
Response. send ( 'Hello IE' )
} )
app. post ( '/server' , ( Request, Response ) => {
Response. setHeader ( 'Access-Control-Allow-Origin' , '*' )
Response. send ( 'Hello Ajax-4' )
} )
app. listen ( 8000 , ( ) => {
console. log ( '8000 running meproject express' )
} )