2013-05-10 43 views
0

我需要檢查具有Ajax請求的Apache Web服務器的htdocs文件夾中是否存在特定文件。我是Ajax新手。請讓我知道我的方法是否正確。如何檢查Apache Web服務器的htdocs文件夾中是否存在文件

我正在用Javascript編寫以下函數來執行上述操作。

我考慮過的網址是:「http://film.ts」。

function checkURL(url){ 
    var Ajaxhttp; 
    if (window.XMLHttpRequest){ 
     Ajaxhttp=new XMLHttpRequest(); 
    } 
    else{// code for IE6, IE5 
     Ajaxhttp=new ActiveXObject("Microsoft.XMLHTTP"); 
    } 

    Ajaxhttp.open("HEAD",url,true); 
    Ajaxhttp.onreadystatechange=function(){ 
     if (Ajaxhttp.readyState==4 && Ajaxhttp.status == 200){ 
      data.playoutInfo._playoutUrls[0] = url; 
     } 
     else if(Ajaxhttp.status == 404){ 
      data.playoutInfo._playoutUrls[0] = "http://San_Diego_Clip.ts"; 
     } 
    } 
    Ajaxhttp.send(); 
} 

對於上述代碼,即使文件不存在,我也會將狀態設置爲200。如果我能通過其他方式實現這一點,請告訴我。

+0

這應該工作得很好。由於配置錯誤,請檢查服務器是否因404錯誤頁面的文本而返回200個狀態。 – Quentin 2013-05-10 12:09:41

回答

0

您應該使用Ajaxhttp.open("GET",url,true);發出GET請求。檢查的xhr.open的API在

https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest

void open(
    DOMString method, 
    DOMString url, 
    optional boolean async, 
    optional DOMString user, 
    optional DOMString password 
); 

所以,你有200的所有時間HEAD請求。

+0

爲什麼只是因爲您提出了HEAD請求才能獲得200? http://jsfiddle.net/pf3KA/ – Quentin 2013-05-10 12:06:31

+0

是的,我犯了一個錯誤 – 2013-05-10 12:13:10

+0

不,如果你想查詢有關服務器的選項,那麼你做一個[選項請求](http://www.w3.org/Protocols/) RFC2616/RFC2616-sec9.html#sec9.2)。 HEAD的目的是獲取您獲得GET請求時將獲得的HTTP標頭。這是查找資源是否存在(例如不是404)而不要求服務器向您發送整個資源的想法。你用哪種瀏覽器進行調試的方式是 – Quentin 2013-05-10 12:15:18

0

在你的htdocs文件夾中創建三個[3]文件1)searchFile.php 2)ajaxreq.php,創建一個名爲IamAfile.txt的文件。

的searchFile.php = 內部= ======寫:

<html> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"> 
<title>Looking For A File</title> 

</head> 

<body> 

<div class="repoter">Content for class "repoter" Goes Here</div> 



<script src="http://code.jquery.com/jquery-1.9.1.js"></script> 
<script type="text/javascript" > 
$(document).ready(function() { 
$.post("ajaxreq.php", 
    { 
    anyFile:"IamAfile.txt" 

    }, 
    function(data,status){ 
    $(".repoter").html(data); 
    } 
) 
}); 
</body> 
</html> 

==結束的searchFile.php ==

現在

==裏面的ajaxreq.php == ========寫這個:

<?php 
if (isset($_POST['anyFile'])) { 
$anyFile=$_POST['anyFile'];//your in need file 
$ineedFile=$anyFile; 
if (file_exists($ineedFile)) { 

//if the in need file is htdocs folder report this 

$report="The file is here. Named : <a href='$ineedFile' >Open The File Here</a>" ; 

    } 
    else if (!file_exists($ineedFile)) { 

//no such in need file report this 

$report="No Such File In Mentioned Directory"; 

    } 
else{ 
$report="Sorry Dont Understand your request"; 
exit; 
} 

echo $report; 
} 
?> 

================================================ === ajaxreq.php =============

測試請求

,如果在你的htdocs目錄中創建的所有文件複製完這/searchFile.php粘貼到您的瀏覽器,回車。這我將如何使用jQuery的Ajax

相關問題