封装原生Ajax请求

封装get请求

  1. /**
  2. * Ajax的Get请求辅助方法
  3. * @param {String} url 请求后台的地址
  4. * @param {Function} callback 请求成之后,返回数据成功,并且调用此方法,这个方法接受一个参数就是后台返回的数据。
  5. * @return undefined
  6. */
  7. function ajaxGet(url, callback) {
  8. var xhr = new XMLHttpRequest();
  9. xhr.open('GET', url, true);
  10. xhr.send();
  11. xhr.onreadystatechange = function () {
  12. if (xhr.readyState == 4 && xhr.status == 200) {
  13. callback(xhr.responseText);
  14. }
  15. }
  16. }
  17. // 调用
  18. ajaxGet('/user.json', function (data) {
  19. console.log(data);
  20. });

封装post请求

  1. function ajaxPost(url, data, callback) {
  2. var xhr = new XMLHttpRequest();
  3. xhr.open('POST', url, true);
  4. xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
  5. xhr.send(data);
  6. xhr.onreadystatechange = function () {
  7. if (xhr.readyState == 4 && xhr.status == 200) {
  8. callback(xhr.responseText);
  9. }
  10. }
  11. }
  12. // 调用
  13. ajaxPost('/api/user', 'id=9&com=aicoder', function (data) {
  14. // 后台返回的数据就是 字符串类型。要转成json,必须自己手动转换。
  15. var user = JSON.parse(data);
  16. console.log(user.id);
  17. console.log(user.com);
  18. });