我有一个用PHP创建的“学生”对象/模型,我使用它的setter方法用每行CSV中每个单元格上的值设置其字段。我在将学生数组解析为JSON对象时遇到麻烦。
read_student_csv.php
echo json_encode(getPopulatedStudentCSV());// doesn't seem to parse correctly
function getPopulatedStudentCSV(){
$studentList = [];
$csvFile = $_FILES["csvFile"]["tmp_name"];
$student_csv_temp_file_location = $_FILES["csvFile"]["tmp_name"];
$row = 1;
$handle = fopen($student_csv_temp_file_location, "r");
if ($handle !== FALSE) {
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
$rowCellCount = count($data);
//echo "<p> $rowCellCount fields in row: $row: <br /></p>\n";
$row++;
$student = new Student();
for ($cell=0; $cell < $rowCellCount; $cell++) {
if($row != 2){
if($cell == 0) //student number
{
$student->setStudentNo($data[$cell]);
}
else if($cell == 1) //student last name
{
$student->setLastName($data[$cell]);
}
else if($cell == 2) //student first name
{
$student->setFirstName($data[$cell]);
}
else if($cell == 3) //student middle name
{
$student->setMiddleName($data[$cell]);
}
}
}
$studentList[] = $student;
}
fclose($handle);
}
return $studentList;
}
jsfile
function displayCSVPreview(){
var csvFile = $('#browseFiles')[0].files[0];
var formData = new FormData();
formData.append('csvFile', csvFile);
//alert("FormData: "+formData);
$.ajax({
url: 'script/read_student_csv.php',
type: 'POST',
data: formData,
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
success: function (students) {
console.log("Students : " + students);
console.log("Length: "+ students.length);
for(var i = 1; i < students.length; i++){
$('#studentcsvpreviewtable').append(
"<tr>"+
"<td>" + students[i] +"</td>" +
"<td>" + students[i]['lastName'] + "</td>" +
"<td>" + students[i]['firstName'] + "</td>" +
"<td>" + students[i]['middleName'] + "</td>" +
"</tr>"
);
}
},
error: function (x, e) {
handleError(x,e);
}
});
}
student[i]
返回由 read_student_csv.php 的getPopulatedStudentsCSV()
函数的响应返回的值的每个 。
如果我执行student[i]['lastName']
,则会得到一个“ 未定义”值。
我不知道如何使用键和值将$studentList[]
正确解析为JSON。 json_encode()
似乎做得不正确。
下面两行返回
console.log("Students : " + students);
console.log("Length: "+ students.length);
学生: [{{studentNo“:null,” lastName“:null,” firstName“:null,” middleName“:null},{” studentNo“:” 12345“,” lastName“:” Doe“,” firstName“:” John Sam“,” middleName“:” Man“},{” studentNo“:” 23456“,” lastName“:” Nuggets“,” firstName“:” Ashton“,” middleName“:” Alvin“}]
长度:256
显示256的长度,因为我认为它计算输出中的每个字符。哪个不正确。
任何建议,我将不胜感激。
谢谢。