Ajax发送FormData并检索多维数组

时间:2017-08-14 18:16:14

标签: javascript php jquery codeigniter

好吧所以我有一个表单,您可以选择一个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);
            }
        }
    }
}

1 个答案:

答案 0 :(得分:1)

如果您希望能够在javascript中使用数据,那么您将需要应用密钥。所以在你的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来遍历行并执行您想要执行的操作。使用您的控制台查看result.rows,您将看到我的意思。

相关问题