Created
March 7, 2016 02:04
-
-
Save imzhi/ce2f50179783697594da to your computer and use it in GitHub Desktop.
简单封装的ajax请求
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| function ajax(opts) { | |
| var options = { | |
| type: opts.type || 'get', | |
| url: opts.url, | |
| data: opts.data || '', | |
| success: opts.success | |
| }; | |
| if (!options.url) { | |
| alert('报错'); | |
| } | |
| var r = new XMLHttpRequest(), fu = '?'; | |
| r.onreadystatechange = get_data; | |
| if (options.type === 'get') { | |
| options.url.indexOf('?') > -1 && (fu = '&'); | |
| r.open(options.type, options.url + fu + options.data, true); | |
| r.send(null); | |
| } else { | |
| r.open(options.type, options.url, true); | |
| options.type === 'post' && r.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); | |
| r.send(options.data); | |
| } | |
| function get_data() { | |
| if (r.readyState == 4) { | |
| if (r.status == 200) { | |
| options.success(r.responseText); | |
| } else { | |
| alert('接收数据出错'); | |
| } | |
| } | |
| }; | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| ajax({ | |
| type: 'get', | |
| url: 'get.php', | |
| data: 'send_get=我是get', | |
| success: function(res) { | |
| var o = JSON.parse(res); | |
| alert(o.data); | |
| } | |
| }); | |
| ajax({ | |
| type: 'post', | |
| url: 'post.php', | |
| data: 'send_post=我是post', | |
| success: function(res) { | |
| var o = JSON.parse(res); | |
| alert(o.data); | |
| } | |
| }); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment