V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
APICloud
V2EX  ›  编程

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

  •  
  •   APICloud · 2017-08-18 17:41:06 +08:00 · 2891 次点击
    这是一个创建于 2436 天前的主题,其中的信息可能已经有所发展或是发生改变。

    很多开发者对 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 开发者“常山赵子云”原创提供,欢迎转载和使用!

    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   864 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 21:53 · PVG 05:53 · LAX 14:53 · JFK 17:53
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.