《2019年3月26日》【连续 538天】
标题:ajax-fn2.html;
内容:
// ## version 1 =======================================
// function ajax (method, url, params) {
// var xhr = new XMLHttpRequest()
// xhr.open(method, url)
// xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
// params = params || null
// xhr.send(params)
// xhr.onreadystatechange = function () {
// if (this.readyState !== 4) return
// console.log(this.responseText)
// }
// }
// // ## version 2 ========================================
// function ajax (method, url, params) {
// var xhr = new XMLHttpRequest()
// if (method === 'GET') {
// url += '?' + params
// }
// xhr.open(method, url)
// var data = null
// if (method === 'POST') {
// xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
// data = params
// }
// xhr.send(data)
// xhr.onreadystatechange = function () {
// if (this.readyState !== 4) return
// console.log(this.responseText)
// }
// }
// // ## version 3 ========================================
// function ajax (method, url, params) {
// var xhr = new XMLHttpRequest()
// // 将 object 类型的参数转换为 key=value&key=value
// if (typeof params === 'object') {
// var tempArr = []
// for (var key in params) {
// var value = params[key]
// tempArr.push(key + '=' + value)
// }
// // tempArr => [ 'key1=value1', 'key2=value2' ]
// params = tempArr.join('&')
// // params => 'key1=value1&key2=value2'
// }
// if (method === 'GET') {
// url += '?' + params
// }
// xhr.open(method, url)
// var data = null
// if (method === 'POST') {
// xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
// data = params
// }
// xhr.send(data)
// xhr.onreadystatechange = function () {
// if (this.readyState !== 4) return
// console.log(this.responseText)
// }
// }
// ajax('GET', 'time.php', { id: 1 })
// ajax('POST', 'add.php', { key1: 'value1', key2: 'value2' })
// ajax('POST', 'add.php', 'key1=value1')