fetch.lua 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. -- fetch 远程请求模版
  2. local fetch_request_tpl = [[
  3. var %s=null;
  4. fetch("%s",{
  5. method: '%s',
  6. body: "%s",
  7. headers: { %s},
  8. })
  9. .then(response => {
  10. if (!response.ok) {
  11. throw new Error('Network response was not ok');
  12. }
  13. if("%s"=="text"){
  14. return response.text();
  15. }else if("%s"=="json"){
  16. return response.json();
  17. }else{
  18. return "我也不知道要返回什么格式";
  19. }
  20. })
  21. .then(data=>{
  22. %s = data
  23. })
  24. .catch(error => {
  25. console.error('Error:', error);
  26. });
  27. ""
  28. ]]
  29. --fetch异步请求
  30. --path:用于选择tab页
  31. --result_type:结果返回类型 0文本 1列表 2字典
  32. --method:POST /GET
  33. -- url: 请求URL
  34. --head:请求头
  35. --param:参数 POST请求下,有值
  36. --return_type:text/json
  37. --js_var:结果回写到js_var
  38. --retry_time:等待次数
  39. --sleep_timeout:等待间隔时间
  40. function fetch(path,result_type,method,url,head,param,return_type,js_var,retry_time,sleep_timeout)
  41. local head_str = ""
  42. for k,v in pairs(head) do
  43. head_str=head_str..string.format('"%s":"%s",',k,v)
  44. end
  45. local fetch_run_js = string.format(fetch_request_tpl,js_var,url,method,param,head_str,return_type,return_type,js_var)
  46. --print(fetch_run_js)
  47. local ok,ret = browser_executejs(path,1000*10,0,fetch_run_js)
  48. wait_jsvar_notnull(path,js_var,retry_time,sleep_timeout)
  49. return browser_executejs(path,1000*10,result_type,js_var)
  50. end
  51. --守候等待js变量不为null
  52. function wait_jsvar_notnull(path,js_var,retry_time,sleep_timeout)
  53. local flag=false
  54. local i=1
  55. local check_js_var_tpl = 'if(%s){"true"}else{"false"}'
  56. local run_js=string.format(check_js_var_tpl,js_var)
  57. repeat
  58. local ok,ret = browser_executejs(path,1000*2,0,run_js)
  59. if ok=="ok" and ret=="true" then
  60. flag=true
  61. else
  62. print("waitting")
  63. browser_sleep(sleep_timeout)
  64. end
  65. i=i+1
  66. until flag or i>retry_time
  67. end