2016-09-23 134 views
0

将表单提交给api后,如果表单数据已更新并显示状态,则会呈现一个加载页面,需要每60秒检查一次,每隔1秒检查一次。有没有办法继续使用vue-resource选项来重试ajax请求并设置时间间隔和超时?在他们的documentation他们有一个超时选项,但没有间隔。这是我到目前为止:如何在页面加载时使用vue资源定期轮询后端api?

<template> 
    <div v-if="location === 'updated'">Location Updated!</div> 
    <div v-if="location === 'error'">Update failed, check back later!</div> 
    <div v-if="location === 'pending'">Loading...</div> 
</template> 

<script> 
... 

data: function() { 
    return { orderStatus: 'pending' } 
} 

ready: function() { 
    this.$http.get('/location/12', { timeout: 60000, interval: 1000 }).then((response) => { 
     this.orderStatus = response.body.order_status 
    } 
    } 
</script> 
+0

'setInterval'或'setTimeout'? – BenM

+0

@BenM我想都 – cvDv

回答

0

Web套接字应该是理想的答案。

但如果你的目标是要看看是否表单数据已更新,你可以做轮询这些方式

简单而不递延

(function poll(){ 
    setTimeout(function(){ 
     $.ajax({ url: "server", success: function(data){ 
     //Setup the next poll recursively if order status is not updated 
     if (orderStatus not update) 
      poll() 
     else 
      display order status 
     }, dataType: "json"}); 
    }, 30000); 
})(); 

递延:

// The polling function 
function poll(fn, timeout, interval) { 
    var dfd = new Deferred(); 
    var endTime = Number(new Date()) + (timeout || 2000); 
    interval = interval || 100; 

    (function p() { 
      // If the condition is met, we're done! 
      if(fn()) { 
       dfd.resolve(); 
      } 
      // If the condition isn't met but the timeout hasn't elapsed, go again 
      else if (Number(new Date()) < endTime) { 
       setTimeout(p, interval); 
      } 
      // Didn't match and too much time, reject! 
      else { 
       dfd.reject(new Error('timed out for ' + fn + ': ' + arguments)); 
      } 
    })(); 

    return dfd.promise; 
} 

// Usage: ensure order status is updated 
poll(function() { 
    return response.body.order_status == "updated"; 
}, 2000, 150); 
相关问题