<!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>
JSON語法的問題,如何理解for循環(huán)那里
滴答滴滴答滴
2016-12-12 11:25:27