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進一步處理?
謝謝。
有什麼輸出'console.log(data);'在你的javascript控制檯中?有沒有控制檯錯誤? – Robbert
感謝羅伯特 - 我使用了Firebug,並且控制檯部分沒有顯示任何錯誤。 – PeterK900