为什么 AJAX 调用、Laravel、JQuery 后 return()->response 不起作用?

发布于 2025-01-11 06:28:52 字数 2807 浏览 0 评论 0原文

JQuery(AJAX 调用):

$('#frm').validate({
  rules: {
    date1: {
      required: true,
    },
    date2: {
      required: true,
    },  
  },

  submitHandler: function(form) {
            let formD = new FormData(form);
    
    //formD.append(Report_id, $('#inp_2').val());
    
    $.ajax({            
      url: form.action,
      type: form.method,
      data: formD,
      processData: false,
      contentType: false,
      cache: false,
      success:function(data)
      {
        toastr.success(data);
        
      }, 
      error:'', 
    })
  }
});

控制器:

public function product_list_report(Request $request)
{
    $validator = Validator::make($request->all(),[
        "date1" => 'required',
        "date2" => 'required',
    ]);

    if($validator->fails()){return dd("Errored");}
    $f = time().'_'.'mybin_report.csv';
    $headers = array(
        'Content-Type' => 'application/vnd.ms-excel; charset=utf-8',
        'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0',
        'Content-Disposition' => 'attachment; filename='.$f,
        'Expires' => '0',
        'Pragma' => 'public',
    );
    $filename =  public_path("files/".$f);
    if(isset($request->inp_2))
    {
        $data = DB::table('products')
        ->select('products.id as product_id', 'products.name as product_name', 'products.format', 'products.code as product_code', 'products.description', 'products.created_at')
        ->orderBy('products.created_at', 'DESC')
        ->get();
        $columns = array('Product_id', 'Name', 'Format', 'Code', 'Description', 'Created On');

        if (!File::exists(public_path()."/files")) {
            File::makeDirectory(public_path() . "/files");
        }
        //creating the download file
        $file = fopen('php://output', 'w');
        fputcsv($file, $columns);

        $handle = fopen($filename, 'w');
        foreach ($data as $dt) {
            fputcsv($handle, [$dt->product_id, $dt->product_name, $dt->format, $dt->product_code, $dt->description, $dt->created_at,]);    
        }
        $response = array(
            'status' => 'success',
            'response_code' => 200,
            'msg' => 'Successfully created',
        );
    }
    echo json_encode($response);
    fclose($handle);
    return response()->download($filename, $f, $headers);
}

以下是 jquery toastr 响应,这意味着代码已经完成 ajax 调用的成功部分 输入图片description here

然后它返回到控制器,当它执行 return response()->download($filename, $f, $headers); 时,文件应该被下载这不是发生这种情况,没有 AJAX 调用,文件就被下载了,我不明白为什么它不起作用。

任何帮助将不胜感激。

The JQuery(AJAX call):

$('#frm').validate({
  rules: {
    date1: {
      required: true,
    },
    date2: {
      required: true,
    },  
  },

  submitHandler: function(form) {
            let formD = new FormData(form);
    
    //formD.append(Report_id, $('#inp_2').val());
    
    $.ajax({            
      url: form.action,
      type: form.method,
      data: formD,
      processData: false,
      contentType: false,
      cache: false,
      success:function(data)
      {
        toastr.success(data);
        
      }, 
      error:'', 
    })
  }
});

Controller:

public function product_list_report(Request $request)
{
    $validator = Validator::make($request->all(),[
        "date1" => 'required',
        "date2" => 'required',
    ]);

    if($validator->fails()){return dd("Errored");}
    $f = time().'_'.'mybin_report.csv';
    $headers = array(
        'Content-Type' => 'application/vnd.ms-excel; charset=utf-8',
        'Cache-Control' => 'must-revalidate, post-check=0, pre-check=0',
        'Content-Disposition' => 'attachment; filename='.$f,
        'Expires' => '0',
        'Pragma' => 'public',
    );
    $filename =  public_path("files/".$f);
    if(isset($request->inp_2))
    {
        $data = DB::table('products')
        ->select('products.id as product_id', 'products.name as product_name', 'products.format', 'products.code as product_code', 'products.description', 'products.created_at')
        ->orderBy('products.created_at', 'DESC')
        ->get();
        $columns = array('Product_id', 'Name', 'Format', 'Code', 'Description', 'Created On');

        if (!File::exists(public_path()."/files")) {
            File::makeDirectory(public_path() . "/files");
        }
        //creating the download file
        $file = fopen('php://output', 'w');
        fputcsv($file, $columns);

        $handle = fopen($filename, 'w');
        foreach ($data as $dt) {
            fputcsv($handle, [$dt->product_id, $dt->product_name, $dt->format, $dt->product_code, $dt->description, $dt->created_at,]);    
        }
        $response = array(
            'status' => 'success',
            'response_code' => 200,
            'msg' => 'Successfully created',
        );
    }
    echo json_encode($response);
    fclose($handle);
    return response()->download($filename, $f, $headers);
}

The following is th jquery toastr response which means the code is already done with the success part of the ajax call
enter image description here

then it comes back to the controller an when it executes return response()->download($filename, $f, $headers); the file should get downloaded which is not happening, without the AJAX call the file was being downloaded and I can't figure out why it ain't working.

Any help will be appreciated.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文