我希望在一段时间后显示提示消息:“您要继续吗?”如果用户选择是,则必须在后台运行ajax调用,否则取消ajax调用。请告诉我如何在ajax调用响应中设置时间条件。
我希望在一段时间后显示提示消息:“您要继续吗?”如果用户选择是,则必须在后台运行ajax调用,否则取消ajax调用。请告诉我如何在ajax调用响应中设置时间条件。
在JavaScript或jQuery中使用setTimeout()函数
var time = 5000;
setTimeout(function() {
if (confirm('Do you want continue?')) {
var root = 'http://jsonplaceholder.typicode.com';
$.ajax({
url: root + '/posts/1',
method: 'GET'
}).then(function(data) {
console.log(data);
});
} else {
// Do nothing!
}
}, time)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
// Assign handlers immediately after making the request,
// and remember the jqXHR object for this request
var jqxhr = $.ajax( "example.php" )
.done(function() {
alert( "success" );
})
.fail(function() {
alert( "error" );
})
});
//when user pressed no call the below function if the ajax is not completed
jqxhr.abort()
function longPolling()
{
$.ajax({
//..... your ajax configurations like url, type, dataType...etc
success: function(data){
// your code for handle success response
setTimeout(function(){
longPolling();
},5000) // call again after 5 seconds
},
error: function(xhr){
// your code for handle error response
setTimeout(function(){
longPolling();
},5000) // call again after 5 seconds
}
};
});
longPolling();// call where ever you need
希望它对你有所帮助
window.setTimeout(function () {
if (confirm('Do you want continue?')) {
// Do some ajax?
} else {
// Do nothing!
}
}, 5000);