Yii2:尝试用 ajax 生成一个 csv 文件

Yii2: Trying to generate a csv file with ajax

我正在尝试生成包含一些数据的基本 csv 文件。当我在 ajax 调用中使用警报时,它会显示数据(因此有数据传递),但是当我单击按钮时,它不会生成 CSV 文件。我是 yii2 的新手,所以我还在学习。

已更新 我已经更改了文件

//查看export/index.php

Pjax::begin();

$form = ActiveForm::begin([
    'action'  => yii\helpers\Url::to(['cms-export/index']),
    'options' => ['data' => ['pjax' => true]],
    'layout'  => 'horizontal',
    'fieldConfig' => [
        'horizontalCssClasses' => [
            'label'   => 'col-sm-2',
            'offset'  => 'col-sm-offset-2',
            'wrapper' => 'col-sm-5',
            'hint'    => 'col-sm-5',
        ],
    ],
]);

    echo $form->field($model, 'language')->dropDownList([//some list]);

    echo $form->field($model, 'filename')->textInput()

    echo Html::submitButton('Submit', ['class' => 'btn btn-primary'])';



ActiveForm::end();

Pjax::end();

//型号

public function generateCsv(){

  header('Content-Type: application/csv');
  header('Content-Disposition: attachment; filename="sample.csv"');

    $data = [datacomeshere];

    $fp = fopen('php://output', 'w');
    foreach ( $data as $line ) {
        fputcsv($fp, $line, ';');
    }
    fclose($fp);

}

//控制器

public function actionIndex()
{

    $model = new Export();

    if ($model->load(Yii::$app->request->post()) && $model->validate()) {

        // validation works, but method does not work
        \common\models\Export::generateCsv();

    }

    return $this->render('index' , ['model' => $model]);

}

当我点击按钮时,它会在 jquery 文件中显示 500 错误

xhr.send( options.hasContent && options.data || null );

我建议采用以下方法,删除整个 JS 代码:

使 link 成为真实的。有一个 GET 请求是有意义的,因为您只是通过调用获取数据。

<div class="modal-button-row">
    <a href="cms-export/download" id="export-trigger" class="btn btn-success pull-left">Export</a>
</div>

现在修改操作(可能在 CmsExportController 中)并使用 Yii download capability:

public function actionDownload() {
    $csv = Export::generateCsvSomehow(); // this should return a csv string
    return \Yii::$app->response->sendContentAsFile($csv, 'sample.csv', [
           'mimeType' => 'application/csv', 
           'inline'   => false
    ]);
}

指南中的更多信息:here

你还需要删除Pjax, since it will do its own stuff with links and forms via JS! Or you have to configure Pjax, e.g. with $formSelector,这超出了这个问题的范围。

一个问题肯定是常规操作调用总是创建 headers、cookie 和一些内容(甚至是空字符串,例如,如果您忘记了带有 $this->render(...) 的 return 语句) 发送到浏览器。我怀疑您遇到了一些 Headers already sent 错误。所以这必须被抑制,以便您的 CSV 代码控制。

尝试以下操作:

 public function actionIndex() {
    $model = new Export();
    if ($model->load(Yii::$app->request->post()) && $model->validate()) {
        \common\models\Export::generateCsv();
        Yii::$app->response->isSent = true;
    } else {
        return $this->render('index' , ['model' => $model]);
    }
}

顺便说一句:如果该调用没有更改数据,请在表单中使用 method: GET。这是一个 HTTP 标准。 POST 在添加或更改内容时使用。

不过,我会推荐 my other approach using Response::sendContentAsFile()。这也适用于您的 ActiveForm。如该答案中所述,您必须删除或配置 Pjax。