好吧,我有一个表单,您可以在其中选择 CSV 文件,当您点击 sales_importer 按钮时,我希望我的 java 调用我的 php 函数并获取返回的多维数组,然后进行后续处理。当我运行以下代码时,我收到带有多维值数组的警报框,但它看起来像是字符串形式。当我执行 alert(result[0][0]);
时,我的警报框中会出现 [
。
我尝试将 ajax 调用中的 dataType 更改为 json,但它失败了,但我仍然从浏览器收到 200 响应。对于可能发生的情况/如何修复它有什么建议吗?
js
$('body').on('click', '#sales_importer', function() {
$.ajax({
type: 'POST',
data: new FormData($('form[id="import_form"]')[0]),
cache: false,
contentType: false,
processData: false,
url: admin_url+'Clients/import',
success: function(result){
alert(result);
}
});
});
php
public function import()
{
if ($this->input->is_ajax_request()) {
if (isset($_FILES['client_file_csv']['name']) && $_FILES['client_file_csv']['name'] != '') {
// Get the temp file path
$tmpFilePath = $_FILES['client_file_csv']['tmp_name'];
// Make sure we have a filepath
if (!empty($tmpFilePath) && $tmpFilePath != '') {
// Setup our new file path
$newFilePath = TEMP_FOLDER . $_FILES['client_file_csv']['name'];
if (!file_exists(TEMP_FOLDER)) {
mkdir(TEMP_FOLDER, 777);
}
if (move_uploaded_file($tmpFilePath, $newFilePath)) {
$import_result = true;
$fd = fopen($newFilePath, 'r');
$rows = array();
while ($row = fgetcsv($fd)) {
$rows[] = $row;
}
$data['total_rows_post'] = count($rows);
fclose($fd);
echo json_encode($rows);
}
unlink($newFilePath);
}
}
}
}
最佳答案
如果您希望能够在 JavaScript 中使用数据,那么您将需要应用 key 。所以在你的 PHP 中:
echo json_encode( array('rows' => $rows) );
现在允许您访问 jQuery AJAX 成功函数中的行:
success: function(result){
// rows available as result.rows
if( result.rows ){
// Do something with result.rows...
console.log( result.rows );
$.each( result.rows, function(i, arr){
console.log( arr );
});
}
}
请记住,result.rows 将是一个 javascript 对象,因此您需要使用 jQuery 的each 来循环遍历行并执行您想要执行的操作。使用控制台查看 result.rows,您就会明白我的意思。
关于javascript - Ajax 发送 FormData 并检索多维数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45680578/