當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
javascript --- 实现Ajax的代码
生活随笔
收集整理的這篇文章主要介紹了
javascript --- 实现Ajax的代码
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
直接上代碼,(前幾天項目出差部署去叻)
const ajax = function (options = {}) {option.type = (options.type || 'GET').toUpperCase();let data = [];for(let i in options.data) {data.push(encodeURIComponent(i) + '=' + encodeURIComponent (options.data[i]));}data = data.join('&');const xhr = new XMLHttpRequest();xhr.onreadystatechange = function () {if (xhr.readyState === 4) {const status = xhr.status;if (status >= 200 && status < 300) {options.success &&options.success(JSON.parse(xhr.responseText),xhr.responseXML);} else {options.error && options.error(status);}}};if (options.type === 'GET') {xhr.open('GET', options.url + '?' + data, true);xhr.send(null);} else if (options.type === 'POST') {xhr.open('POST', options.url, true);xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');xhr.send(data);} }; 參考 《vue.js實戰》P231總結
以上是生活随笔為你收集整理的javascript --- 实现Ajax的代码的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Codeforces Global Ro
- 下一篇: 设置Idea护眼背景色 简单明了