2011-10-15 39 views
4

我做一些consecutives(recrusive)Ajax請求的PHP文件寫入請求參數到一個文件:file_put_contents訪問被拒絕的幾個AJAX請求(但同步)?

make_ajax(s) 
{ 
var xhr = new XMLHttpRequest(); 
xhr.onreadystatechange=function() 
{ 
    if(this.readyState == 4 && this.status == 200) 
    { 
    if(s>0) 
    make_ajax(s-1) 
    } 
}; 
xhr.open('POST','write.php?s='+s+'&string=somelongstring',true);//url + async/sync 
... 
xhr.send(null); 
} 
make_ajax(15);//start request 

write.php:

file_put_contents('test.txt',$_GET['s']); 

看來,服務器返回ajax請求,在它關閉text.txt文件之前,因此由recrusive發送的下一個ajax請求會得到Access Denided錯誤,因爲似乎該文件仍然由previrios ajax請求(它返回的事件)打開?我甚至用async = false測試了這個腳本,但是我得到了同樣的錯誤?如何在關閉文件之前避免該php腳本返回?

注意:我沒有使用會話,我只是發送數據到服務器保存在一個文件。

NOTE2:在這裏我做了一個簡單的例子,在realty我使用這種方法上傳文件的塊與ajax和mozSlice方法。全碼:

  function uploadFileXhr(o,start_byte) 
      { 

       var total=o.size; 
       var chunk; 

       var peice=1024 * 1024;//bytes to upload at once 

       var end_byte=start_byte+peice; 
       var peice_count=end_byte/peice; 
       $('#debug').html(peice_count); 
       var is_last=(total-end_byte<=0)?1:0; 
       chunk=o.mozSlice(start_byte, end_byte); 

       var xhr = new XMLHttpRequest();//prepare xhr for upload 

       xhr.onreadystatechange=function() 
       { 
        if(this.readyState == 4 && this.status == 200) 
        { 
         if(is_last==0) 
         { 
          uploadFileXhr(o,end_byte); 
         } 
        } 
       }; 

       xhr.open('POST','upload.php',true);//url + async/sync 
       xhr.setRequestHeader("Cache-Control", "no-cache"); 
       xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');//header 
       xhr.setRequestHeader('Content-Type', 'multipart/form-data');//type for upload 
       xhr.send(chunk);//send request of file 
      } 
uploadFileXhr(file_input,0);//start recrusive call 

upload.php的:

$flag =($_GET['start']==0) ? 0:FILE_APPEND; 
file_put_contents($remotePath.$add.$file_name, file_get_contents('php://input'),$flag); 

注3:OK實際上建立了一個解決辦法,以避免錯誤,在upload.php程序:

 $flag =($_GET['start']==0) ? 0:FILE_APPEND; 
     $file_part=file_get_contents('php://input'); 
     while(@file_put_contents($remotePath.$add.$file_name, $file_part,$flag)===FALSE) 
     { 
      usleep(50); 
     } 

但仍我無法解釋爲什麼我在第一種情況下得到訪問錯誤,因此等待評論!

+0

您究竟在哪裏得到「訪問被拒絕」錯誤?什麼是確切的錯誤信息? –

+0

'file_put_contents()'被阻塞。直到文件關閉,腳本纔會完成。 – rid

+0

這是錯誤:警告:fopen(js/test.txt)[function.fopen]:未能打開流:權限在C:\ wamp \ www中拒絕(我嘗試使用標準fopen和file_put_contents,同樣的問題) – albanx

回答

0

目標文件(test.txt)中是否出現任何內容?即它是否在之後發生第一個請求或立即失敗?該錯誤表明服務器無法寫入文件。這可能是因爲某個其他進程正在使用該文件,或者因爲Web服務器對該文件沒有寫入權限。只是爲了消除這些明顯的問題,確保您的Web服務器實際上被允許寫入文件。

+0

是的,服務器無法讀取文件幾秒鐘,我創建了一個解決方案(請參閱NOTE3),但是,我仍然不知道爲什麼會發生在使用wamp進行本地主機測試時。 – albanx