-
ajax向服务器异步发送javascript和xml,ajax利用
xmlHttpRequest
对象向服务器发送请求,然后浏览器继续做其它的事,等服务器返回响应内容后,再利用javscript操作DOM从而更新页面 -
可以在不重新加载整个页面的情况下,与服务器交换数据,从而更新部分网页
-
实现过程:
-
创建
xmlHttpRequest
对象, -
调用open方法与服务器建立连接
-
调用send方法,把数据发送给服务器
-
通过xmlHttpRequest对象提供的
onReadyStateChange
监听服务器端的通信状态- 状态分5种,分别取值为0,1,2,3,4
-
接收并处理服务器端向客户端响应的数据结果
-
把数据结果更新到HTML页面中
-
-
封装Ajax:
//封装一个ajax请求 function ajax(options) { //创建XMLHttpRequest对象 const xhr = new XMLHttpRequest() //初始化参数的内容 options = options || {} options.type = (options.type || 'GET').toUpperCase() options.dataType = options.dataType || 'json' const params = options.data //发送请求 if (options.type === 'GET') { xhr.open('GET', options.url + '?' + params, true) xhr.send(null) } else if (options.type === 'POST') { xhr.open('POST', options.url, true) xhr.send(params) //接收请求 xhr.onreadystatechange = function () { if (xhr.readyState === 4) { let status = xhr.status if (status >= 200 && status < 300) { options.success && options.success(xhr.responseText, xhr.responseXML) } else { options.fail && options.fail(status) } } } }
//使用方式: ajax({ type: 'post', dataType: 'json', data: {}, url: 'https://xxxx', success: function(text,xml){//请求成功后的回调函数 console.log(text) }, fail: function(status){////请求失败后的回调函数 console.log(status) } })