HttpUtils.js 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. class HttpUtils{
  2. request(option) {
  3. if (String(option) !== '[object Object]') return undefined
  4. option.method = option.method ? option.method.toUpperCase() : 'GET'
  5. option.data = option.data || {}
  6. var formData = []
  7. for (var key in option.data) {
  8. formData.push(''.concat(key, '=', option.data[key]))
  9. }
  10. option.data = formData.join('&')
  11. if (option.method === 'GET') {
  12. option.url += location.search.length === 0 ? ''.concat('?', option.data) : ''.concat('&', option.data)
  13. }
  14. var xhr = new XMLHttpRequest()
  15. xhr.responseType = option.responseType || 'json'
  16. xhr.onreadystatechange = function () {
  17. if (xhr.readyState === 4) {
  18. if (xhr.status === 200) {
  19. if (option.success && typeof option.success === 'function') {
  20. option.success(xhr.response)
  21. }
  22. } else {
  23. if (option.error && typeof option.error === 'function') {
  24. option.error()
  25. }
  26. }
  27. }
  28. }
  29. xhr.open(option.method, option.url, true)
  30. if (option.method === 'POST') {
  31. xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded')
  32. }
  33. xhr.send(option.method === 'POST' ? option.data : null)
  34. }
  35. }
  36. //导出
  37. module.exports = new HttpUtils();