我想用JQuery检查服务器上是否存在文件。我可以使用Jquery Ajax来执行此操作,但是我需要一个侦听器,该侦听器在服务器上侦听文件的存在,如果存在,则触发一些操作。
这里是一个示例:
client--> checks on server for file(time 0)--> not present
client--> checks on server for file(time 5)--> not present
client--> checks on server for file(time 10)--> file present--> return some message to client.
所以我该如何实现一个侦听器?用来检查服务器上的某些特定文件并在可用时通知用户?
I would start a listener thread on request and pass in a state object that listener would update after detecting the file. Also on the UI thread i would check the status of the state object if it was updated by the listener thread and perform necessary actions. UI thread is basically a jQuery ajax call on a timer.
The ability to run different functions depending on the HTTP Status Code returned by the server was added in jQuery 1.5. So if the server responds with a 200 execute the function needed if file exists and if it returns a 404 execute the function required if it does not.
$.ajax({
statusCode: {
404: function() {
// file not found
},
200: function() {
// file found
}
}
});
For more info see: jQuery.ajax in the jQuery docs.
Edit: From your comments I can see that you need to keep checking until the file exists. If so just wrap the request in a function and then call that function if the file is not found. Use setTimeOut though else you will be spamming the server with connection requests.
You can use ajax polling..means check the server at a particular interval of time .
You can use setInterval function in java script to call a particular function ..And write ajax request in that function .and if the file found , just clear the timer
Check the sample code
var timerForLoadingResult= setInterval(checkServerForFile,4000);//call the fnction in every 4 seconds.write ajax in that function.
function checkServerForFile() {
$.ajax({
type: "POST",
cache: false,
url: url,
success: function (result) {
if(check result) //if the file is on server
{
//do something
clearInterval(timerForLoadingResult) // clear timer
}
; }
});
}