2016-04-25 45 views
0

This post提供使用獲取服務器文件列表的示例代碼作爲示例。以下是我使用的代碼:Javascript調用php函數並接收返回結果

<html lang="en-US"> 
<head> 
    <meta charset="UTF-8"> 
    <title>How to create form using jQuery UI</title> 
    <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/pepper-grinder/jquery-ui.css" media="screen" rel="stylesheet" type="text/css"> 
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script> 
    <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js" type="text/javascript"></script> 

    <script type="text/javascript"> 
    $(function() { 
    $.get('getfilename.php', { dir : '/ajax1/' }, function(data) { 
     // you should now have a json encoded PHP array 

     $.each(data, function(key, val) { 
      alert('index ' + key + ' points to file ' + val); 

     }); 
    }, 'json'); 
    alert ("ok"); 
}); 

    </script> 
</head> 
<body> 
<h1>Get file names... </h1> 
</body> 
</html> 

getfilename.php

$dir = $_REQUEST['dir'] ; 
$dir = $_SERVER['DOCUMENT_ROOT'] . $dir; 

$filesArray = array(); 
$Counter = 0; 
$files = scandir($dir); 

foreach ($files as &$file) { 
    if ($file!='.' && $file!='..') { 
     $filesArray[$Counter] = $file; 
     echo $filesArray[$Counter].''; 
     $Counter++; 
    } 
} 

echo json_encode($filesArray); 

我的問題是,JavaScript警告alert('index ' + key + ' points to file ' + val);無法顯示網頁上的任何東西。該腳本正在工作,因爲我在Firebug控制檯日誌中獲得響應。

ajax.jsajax.phpindex.html["ajax.js","ajax.php","index.html"] 

我需要更改腳本以將此信息返回到html頁面,以便我可以使用JSON進一步處理?

謝謝。

+0

有什麼輸出'console.log(data);'在你的javascript控制檯中?有沒有控制檯錯誤? – Robbert

+0

感謝羅伯特 - 我使用了Firebug,並且控制檯部分沒有顯示任何錯誤。 – PeterK900

回答

1

隨着你的調試,你打破了PHP中的JSON輸出。因此,刪除:

echo $filesArray[$Counter].''; 

此外,任何輸出之前,您應該添加JSON頭:

header('Content-Type: application/json'); 

最後,你的PHP文件應該是這樣的:

$dir = $_REQUEST['dir'] ; 
$dir = $_SERVER['DOCUMENT_ROOT'] . $dir; 

$filesArray = array(); 
$files = scandir($dir); 

foreach ($files as &$file) { 
    if ($file!='.' && $file!='..') { 
     $filesArray[] = $file; 
    } 
} 
header('Content-Type: application/json'); 
echo json_encode($filesArray); 
+0

由於他在調用'$ .get'時指定了數據類型'json',所以'Content-Type'頭是多餘的。 – Barmar

+0

你的雞比蛋Barmar年紀大。如果他指定了PHP頭部,那麼稍後他不會關心'dataType'。 – skobaljic

+0

但是他的問題中已經有了代碼,所以不需要修復代碼。 – Barmar