我需要检查服务器上文件的可用性,然后做一些与文件相关的反应。我在每个客户端和服务器端都有文件名和路径,然后我有两种方法来检查可用性。一个来自客户端,另一个来自服务器端。
第一种方式:
客户端:
function check_file()
{
$.ajax({
url:'http://www.example.com/somefile.txt',
type:'HEAD',
error: function()
{
//file not exists
//check again after 5 seconds
setTimeout(function(){
check_file();
}, 5000);
},
success: function()
{
//file exists
//start doing other actions related to the file
action_1();
}
});
}
function action_1()
{
$.ajax({
url:'http://www.example.com/action_1.php',
success: function(data)
{
var result = $.parseJSON(data);
if (result.success)
{
//Changes were applied successfully.
//doing some DOM stuff and notifying the client
//check again after 5 seconds
setTimeout(function(){
check_file();
}, 5000);
}
}
});
}
服务器端(action_1.php):
//update database
echo '{success: true}';
第二种方式:
客户端:
function action_2()
{
$.ajax({
url:'http://www.example.com/action_2.php',
success: function(data)
{
var result = $.parseJSON(data);
if (result.success)
{
//Changes were applied successfully
//doing some DOM stuff and notifying the client
}
setTimeout(function(){
action_2();
}, 5000);
}
});
}
服务器端(action_2.php):
if (file_exists('somefile.txt'))
{
//update database
echo '{success: true}';
}
else
{
echo '{success: false}';
}
在第一种方式,我打电话服务器的两倍(Request/ Response/ Request,请注意第一个请求只要求对HEAD),并且它正在使用Apache's默认方案来检查文件的可用性(我不知道它是如何工作的)。
但是在第二种方式中,我调用了服务器一次,它正在使用PHP file_exists()这意味着它需要先加载PHP environment,然后执行action_2.php。
因为该文件大部分不存在,并且因为它需要处理数百万个请求,那么请您指导我哪种方式更好,为什么?
慕哥9229398
慕沐林林
相关分类