如何检查json响应耗时超过5秒

How to check json response taken longer than 5 seconds?

本文关键字:5秒 响应 json 何检查 检查      更新时间:2023-12-17

下面是我的函数的示例代码。在for循环中,将一个接一个的产品id传递给ajax函数,并从php文件中获取产品价格作为响应,然后编写它和html。

for(var i=0; i < data.products.length; i++){
 var doc = data.products[i];
 $.ajax({ // ajax call starts 
          url: 'product.php',
          data: { product_id: doc.id },
          dataType: 'json',
          success: function(data)
          {
           document.getElementById('price_price'+data.product_id+'').innerHTML = data.products_price;
          }
 });
 }

我发现有时候价格显示起来要花更多的时间。我想检查加载哪个记录需要时间。如何检查以检测何时加载价格超过5秒?

类似的内容。。。。

var ajaxTime= new Date().getTime();
$.ajax({
    type: "POST",
    url: "some.php",
}).done(function () {
    var totalTime = new Date().getTime()-ajaxTime;
    // Here I want to get the how long it took to load some.php and use it further
});

此外,顺便说一句,如果您希望在(i)完成之前阻止发送(i+1)请求,您可能希望使用syncronous ajax请求而不是async。

尝试记录时间戳beforesendsuccesserror

$.ajax({ // ajax call starts 
          url: 'product.php',
          data: { product_id: doc.id },
          dataType: 'json',
          beforeSend: function() {
              console.log(new Date().getSeconds());
          }
          success: function(data)
          {
              console.log(new Date().getSeconds());
              document.getElementById('price_price'+data.product_id+'').innerHTML = data.products_price;
          }
 });

使用setTimeout,如下所示:

var timeoutTimer = setTimeout(function() {
    //  time out!!!.
}, 5000);
$.ajax({ // ajax call starts 
    url : 'product.php',
    data : {
        product_id : doc.id
    },
    dataType : 'json',
    success : function(data) {
        document.getElementById('price_price' + data.product_id + '').innerHTML = data.products_price;
    },
    complete : function() {
        //it's back
        clearTimeout(timeoutTimer);
    }
});