使用promise异步请求,请求服务端中data文件,并返回结果

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title>4.异步请求</title>
	</head>
	<body>
		<script type="text/javascript">
			// promise
	        var url = 'http://localhost/hello.php'
	        function getData (url) {
	            let promise = new Promise((resolve,reject) => {
	                // 创建ajax
	                // 1. 创建 XMLHttp
	                var xmlHttp = new XMLHttpRequest()
	                // 2. 监听发送
	                xmlHttp.onreadystatechange = function () {
	                    if (xmlHttp.readyState == 4) {
	                        if (xmlHttp.status == 200) {
	                            // 成功
	                            resolve(xmlHttp.responseText)
	                        } else {
	                            // 失败
	                            reject('请求失败')
	                        }
	                    }
	                }
	                // 3. 获取url
	                xmlHttp.open("GET",url)
	                xmlHttp.send()
	            })
	            return promise
	        }
	        getData(url).then((res) => {
	            console.log(res)
	        }).catch((e) => {   
	            console.log(e)
	        })
		</script>
	</body>
</html>

打印输出:

 

猜你喜欢

转载自blog.csdn.net/this_name_true/article/details/86101023
今日推荐