|
很多开发者对api.ajax请求效率存在疑问,以下提供较为公正的测试代码,通过api.ajax和标准的XMLHttpRequest请求同一个url进行对比:
- //当前系统时间戳,毫秒
- function curtime(){
- return new Date().getTime();
- }
-
- var ajaxurl = 'http://www**.**.cn/ajax/demo_get.asp';
- //api.ajax请求,无跨域问题
- function GetRequest(){
- var starttime = curtime();
- api.ajax({
- url: ajaxurl,
- dataType:'text',
- cache: true
- }, function (ret, err) {
- if (ret) {
- alert('用时:' + (curtime() - starttime) + "毫秒\n请求结果:\n" + JSON.stringify(ret));
- } else {
- alert('出错了!\n' + '网络状态码:' + err.statusCode + '\n错误码:' + err.code + '\n错误信息:' + err.msg);
- }
- });
- }
-
- //标准XMLHttpRequest,可能会有跨域问题
- function GetXmlRequest(){
- var starttime = curtime();
- var xhr = new XMLHttpRequest();
- xhr.onreadystatechange = function(){
- if(xhr.readyState == 4){
- if(xhr.status == 200){
- alert('用时:' + (curtime() - starttime) + "毫秒\n请求结果:\n" + xhr.responseText);
- }else{
- alert('请求失败:\n状态码:' + xhr.status + "\n结果:" + xhr.responseText);
- }
- }
- }
- xhr.open('GET', ajaxurl, true);
- xhr.send(null);
- }
复制代码 通过弹出的对话框可以很明显的看出,在同样网络环境下,两者并无差别,在许多内部业务的服务器场景下,api.ajax甚至更快。
|
|