我需要将索引二维数组从 PHP 返回到 JavaScript。几天来我一直在寻找解决方案。在客户端,我有 on-change 事件(在选项选择中)调用执行 php 文件的 JavaScript 函数。这个 php 文件从 csv 文件创建一个二维数组,用 json 对该数组进行编码。但是,当我尝试在 JavaScript 中访问数组的元素时,它给了我“未定义”。HTML 文件:
<head>
<script type="text/JavaScript">
var d;
function sendIt() {
if (d) document.body.removeChild(d);
var xmlhttp;
var state=arguments[0].options[arguments[0].selectedIndex].value
d = document.createElement("script");
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200) //ready
{
document.getElementById("arrayresult").innerHTML=xmlhttp.arrayFromPhp;
}
}
xmlhttp.open("GET","recordsbystate.php?state=" + state,true);
xmlhttp.send();
d.type = "text/javascript";
document.body.appendChild(d);
}
</script>
</head>
<body>
<select name="state" onChange="sendIt(this)">
<option selected="selected">Select State</option>
<option value="CA">CA</option>
<option value="CO">CO</option>
<option value="MA">MA</option>
<option value="TX">TX</option>
</select>
<div id="arrayresult"></div>
</body>
</html>
PHP 文件:
$file = 'event_submission.csv';
$data2DArray = array();
$state = $_REQUEST['state'];
echo($state), "\n\n";
//create table with header and column names
print('<table align="left" width="430">');
print('<tr><th colspan="4">AOM DAY 2014</th></tr>');
print('<tr><th>Company</th><th>City</th><th>State</th><th>Event Date</th><th>Event Details</th></tr>');
$delimiter = ",";
if (($handle = fopen($file, "r")) !== FALSE) {
$i = 0;
while (($lineArray = fgetcsv($handle, 10000, $delimiter)) !== FALSE) {
if ($lineArray[7] == $state) {
for ($j=0; $j<count($lineArray); $j++) {
$data2DArray[$i][$j] = $lineArray[$j];
}
print('<tr><td>'.$data2DArray[$i][0].'</td><td>'.$data2DArray[$i][6].'</td><td>'.$data2DArray[$i][7].'</td><td>'.$data2DArray[$i][10].'</td></tr>');
}
$i++;
}
fclose($handle);
}
$json = json_encode($data2DArray);
echo 'var arrayFromPhp = ' . $json . ';';
return true;
?>
有什么建议么?请帮忙....