我对 jQuery 很陌生(一周以来),不明白为什么我不能将 PHP (work.php) 数组分配给 global var imgArrayThumbs
。opendir
我正在调用由 php函数创建的图像名称数组。当我alert(imgArrayThumbs);
刚回来的时候[object Object]
。有人可以帮忙吗?整天都想弄清楚。
脚本.js
var imgArrayThumbs = '';
$.post("work.php", { task: "imgArrayThumbs" }, function(data) {
imgArrayThumbs = data;
});
alert(imgArrayThumbs);
工作.php
include_once 'scripts/functions.php';
if($_POST['task'] == 'imgArrayThumbs'){
imageArray('source/examples/thumbs', 'imgArrayThumbs');
}
elseif ($_POST['task'] == 'imgArray'){
imageArray('source/examples/', 'imgArray');
}
函数.php
function imageArray($dir, $arrayVar){
$arrayName = array();
$iNumber = 0;
$open = opendir ($dir);
while ($file = readdir( $open )){
if($file == "." || $file == ".." || $file == ".DS_Store"){
}else{
$arrayName[$iNumber] = $file;
$iNumber ++;
}
}
closedir ( $open );
for ($i = 0;$i<count($arrayName);$i++){
if ($i == 0) {
echo "\"" . $arrayName[$i] . "\"";
}else{
echo ",\"" . $arrayName[$i] . "\"";
}
}
}
编辑 01
工作版本:
脚本.js:
var imgArrayThumbs = new Array();
$.ajaxSetup({async:false});
$.ajax({
type: 'POST',
url: 'work.php',
data: { task: "imgArrayThumbs" },
success: function(data) {
imgArrayThumbs = data;
},
dataType: 'json'
});
函数.php:
echo json_encode($arrayName); // without loop