2012-09-06 76 views
0

如何將php數組回顯到jquery $ .each函數?

這裏就是我試圖在PHP那麼遠,

    $index = 0; 

        while(!feof($file)) 
        { 
        $singleLine = fgets($file); 
        $totalLines[$index] = $singleLine; 

        ++$index; 
        } 
        echo $totalLines; 

以下是我正在讀回jQuery中......

 $.post("sendFile.php",{fileName: sendFileName}, function(data) 
     { 
       $.each(data, function(index, value) 
       { 
         alert(value); 
       }); 
     }); 

輸出給我數組.. 。當它應該給我Test1,Test2,Test3爲每個數組元素...

+0

嘗試$就通過JSON發送數據,並通過獲得JSON我認爲這將爲你工作 –

+0

@ mayank-swami - $ .post只包裝$ .ajax,所以$ .post是好的。它只需要第四個參數,即格式。例如:$ .post('file.php',{field:value},function(data){..},'json');然後它會被解析爲JSON – temporalslide

回答

2

使用json_encode來編碼您的數據。

echo json_encode($totalLines); 

而且你的PHP代碼可以簡單地寫成如下:(使用file函數讀取整個文件到一個數組)

echo json_encode(file($file)); 
// or if need to skip the empty line and new line char 
echo json_encode(file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES)); 
+0

不知道爲什麼,但json解決了我的問題,感謝解決方案。 –

相關問題