[APICloud | APP 开发技巧] api.ajax 请求耗时测试用例

2017-08-18 17:41:06 +08:00
 APICloud

很多开发者对 api.ajax 请求效率存在疑问,移动应用开发平台 APICloud 为大家提供了较为公正的测试代码,通过 api.ajax 和标准的 XMLHttpRequest 请求同一个 url 进行对比:

  1. //当前系统时间戳,毫秒
  2. function curtime(){
  3. return new Date().getTime();
  4. }
  5. var ajaxurl = 'http://www.w3school.com.cn/ajax/demo_get.asp';
  6. //api.ajax 请求,无跨域问题
  7. function GetRequest(){
  8. var starttime = curtime();
  9. api.ajax({
  10. url: ajaxurl,
  11. dataType:'text',
  12. cache: true
  13. }, function (ret, err) {
  14. if (ret) {
 16.                                         alert('用时:' + (curtime() - starttime) + "毫秒\n 请求结果:\n" + JSON.stringify(ret));
  15. } else {
  16. alert('出错了!\n' + '网络状态码:' + err.statusCode + '\n 错误码:' + err.code + '\n 错误信息:' + err.msg);
  17. }
  18. });
  19. }
  20. //标准 XMLHttpRequest,可能会有跨域问题
 24.                 function GetXmlRequest(){
  21. var starttime = curtime();
  22. var xhr = new XMLHttpRequest();
  23. xhr.onreadystatechange = function(){
  24. if(xhr.readyState == 4){
  25. if(xhr.status == 200){
  26. alert('用时:' + (curtime() - starttime) + "毫秒\n 请求结果:\n" + xhr.responseText);
  27. }else{
  28. alert('请求失败:\n 状态码:' + xhr.status + "\n 结果:" + xhr.responseText);
  29. }
  30. }
  31. }
  32. xhr.open('GET', ajaxurl, true);
  33. xhr.send(null);
  34. }

复制代码

通过弹出的对话框可以很明显的看出,在同样网络环境下,两者并无差别,在许多内部业务的服务器场景下,api.ajax 甚至更快。上述代码由移动应用开发平台 APICloud 开发者“常山赵子云”原创提供,欢迎转载和使用!

2903 次点击
所在节点    编程
0 条回复

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/384007

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX