<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>task_24_01</title></head><body><button id="btn">点我</button><script> function ajax (opts) { var xhr = new XMLHttpRequest () xhr.onreadystatechange = function () { if (xhr.readyState === 4 && xhr.status === 200) { var json = JSON.parse(xhr.responseText); opts.success(json) } if (xhr.readyState === 4 && xhr.status === 404) { opts.error() } }; var dataStr = ""; for (var key in opts.data) { dataStr += key + '=' + opts.data[key] + '&' } dataStr = dataStr.substr(0, dataStr.length - 1); if (opts.type.toLowerCase() === 'get') { xhr.open(opts.type, opts.url + '?' + dataStr, true); xhr.send() } if(opts.type.toLowerCase() === 'post') { xhr.open(opts.type, opts.url, true); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.send(dataStr) } } document.querySelector('#btn').addEventListener('click', function(){ btn = document.querySelector('#btn'); btn.innerHTML = '正在打印'; ajax({ url: 'getData.php', //接口地址 type: 'get', // 类型, post 或者 get, data: { username: 'xiaoming', password: 'abcd1234' }, success: function(ret){ console.log(ret); // {status: 0} btn.innerHTML = '点我' }, error: function(){ console.log('出错了'); btn.innerHTML = '点我' } }) });</script></body></html>
添加回答
举报
0/150
提交
取消