AJAX 返回数据问题

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>AJAX 返回数据问题</title>
</head>
<body>
<script>

// 封装者
// =============================

function ajax (method, url, params, done) {
method = method.toUpperCase()
var xhr = new XMLHttpRequest()

if (typeof params === 'object') {
var tempArr = []
for (var key in params) {
var value = params[key]
tempArr.push(key + '=' + value)
}
params = tempArr.join('&')
}

if (method === 'GET') {
url += '?' + params
}

xhr.open(method, url, false)

var data = null
if (method === 'POST') {
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
data = params
}

xhr.onreadystatechange = function () {
if (this.readyState !== 4) return
// 不应该在封装的函数中主观的处理响应结果
// console.log(this.responseText)
// 你说我太主观,那么你告诉我应该做什么
done(this.responseText)
}

xhr.send(data)
}

// 调用者
// ============================

var onDone = function (res) {
console.log('hahahahaha')
console.log('hohohohoho')
console.log(res)
console.log('做完了')
}
ajax('get', 'time.php', {}, onDone)
</script>
</body>
</html>
原文地址:https://www.cnblogs.com/lujieting/p/10291392.html