http

LEORChn JavaScript HTTP Lib

此腳本不應該直接安裝,它是一個供其他腳本使用的函式庫。欲使用本函式庫,請在腳本 metadata 寫上: // @require https://update.gf.qytechs.cn/scripts/401997/797848/http.js

  1. function http(){
  2. var pointer = 0,
  3. method, url, formed, dofun, dofail, onprogress;
  4. arr(arguments).forEach(function(e){
  5. switch(pointer){
  6. case 0:
  7. e = e.split(' ', 2); // 允许在第一个参数中用空格将 http-method 与 url 隔开,而省去 引号+逗号+引号 的麻烦
  8. method = e[0].toUpperCase();
  9. if(e.length > 1){
  10. pointer++; // 偏移到下一个
  11. e = e[1];
  12. }else break;
  13. case 1: url = e; break;
  14. case 2:
  15. if(e instanceof Function){ // 允许不添加 http-body 而直接撰写行为。
  16. pointer++; // 偏移到下一个
  17. }else{
  18. formed = e;
  19. break;
  20. }
  21. case 3: dofun = e; break;
  22. case 4: dofail = e; break;
  23. case 5: onprogress = e;
  24. }
  25. pointer++;
  26. });
  27. var x = 'ActiveXObject' in window?
  28. new ActiveXObject("Microsoft.XMLHTTP"):
  29. new XMLHttpRequest();
  30. if(location.protocol.includes('https'))
  31. url=url.replace('^http:', 'https:');
  32. x.open(method, url, true);
  33. x.timeout=60000;
  34. x.responseType="text"; // IE要求先open才能设置timeout和responseType
  35. x.onload=dofun;
  36. x.ontimeout=x.onerror= dofail? dofail: null;
  37. x.onprogress=onprogress;
  38. if(formed)
  39. x.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8'); // TODO: 暂不明确IE是否适用
  40. x.send(formed?formed:'');
  41. }
  42. function httpj(){
  43. var a = arr(arguments);
  44. if(!a[0].includes(' ')){
  45. a[0] += ' ' + a[1];
  46. a.splice(1, 1);
  47. }
  48. if(a[1] instanceof Function) a.splice(1, 0, null); // 如果 method+url 之后不是 String 而是 Function,判断为 onSuccess,将一个 null 插入到 formed
  49. while(a.length < 5) a[a.length] = null; // 在剩下的空位填满null
  50. // 始终转换为如此格式:0=method+url, 1=formed, 2=onSuccess, 3=onFail, 4=onProgress
  51. http(a[0], a[1], // method+url, formed
  52. function(){
  53. var j,
  54. stat = this.status,
  55. resp = this.responseText;
  56. try{
  57. j = eval('('+ (resp || '{}') +')');
  58. }catch(e){}
  59. if(Array.isArray(j)) // JSON Array
  60. j = { stat:stat, data:j }
  61. else if(j instanceof Object) // JSON Object
  62. j.stat = stat;
  63. else // Nothing, text/plain
  64. j = { stat:stat, data:resp }
  65. a[2](j);
  66. },
  67. a[3], a[4]); // fail, progress
  68. }
  69.  
  70. // edit: 2020-3-20 2:21
  71. // edit: 2020-4-26 3:50

QingJ © 2025

镜像随时可能失效,请加Q群300939539或关注我们的公众号极客氢云获取最新地址