【问题标题】:Laravel 3: AJAX POST and return Response::download()?Laravel 3:AJAX POST 并返回 Response::download()?
【发布时间】:2013-05-28 00:42:30
【问题描述】:

我正在尝试返回要由客户端下载的文件,但是我注意到我在控制器中作为返回值放置的任何内容都不会返回给客户端。

代码如下:

控制器中的代码,我已经删除了不必要的行

public function post_test()
{

    if(Input::get('receive_email'))
    {

        $pdf = new Fpdf('P', 'pt', array(1240, 1754));

        $pdf->AddPage();

        $generated_pdf = $pdf->Output("", "s");


        $body = View::make('test.email_collision')->with($data)->render();
        $message->body($body);
        $message->attach(
            $generated_pdf,
            Sentry::user()->metadata['first_name'] . '_' . Sentry::user()->metadata['last_name'] . '.pdf',
            'application/pdf');
        $message->html(true);
        $message->send();

        if(Message::was_sent())
        {
    // HERE I want to actually return the file to be downloaded
    // return Response::download($pdf->Output("", "i");
            // return $pdf->Output("", "i");
        } else {
            $errors = new Laravel\Messages();
            $errors->add('errors', __('test.error_email_not_sent'));
            return Redirect::back()
                ->with_errors($errors->messages['errors']);
        }

    }

// Trying to not return anything
    // return View::make('collide');
}

我的 JS 文件中执行 POST 的代码

  $("#gEmail").bind('touchstart click', function() {
    $.ajax({
      url: document.URL,
      type: 'POST',
      data: {
        receive_email: "1"
      }
    })
    .fail(function(error) {
      console.error(error);
    });

    uiComplete.hide();

    init();

  });

【问题讨论】:

  • $message 包含什么?此外,您可以通过对应该返回的数据执行 dd() 来检查问题出在哪里,然后监视开发人员工具上的响应

标签: jquery laravel laravel-3


【解决方案1】:

您有以下JS 代码

$.ajax({
    url: document.URL,
    type: 'POST',
    data: {
      receive_email: "1"
    }
})
.fail(function(error) {
    console.error(error);
});

但是您的代码中没有任何success 回调,因此,无论您从服务器返回/回显什么,它在客户端都不可见/不可用。所以,你需要添加jqXHR.done(),你可以像这样添加它

$.ajax({
    // ...
})
.done(function(data){

})
.fail(function(error) {
    console.error(error);
});

你也可以在fail()之后加一个.always(),比如(有利于调试)

.always(function(a, textStatus, b) {
     if (textStatus == "success") {
         console.log("Success : " + a);
     } else {
         console.log("Error : " + b);
     }
 });

另外,check this answer,它会以某种方式帮助您,例如从服务器设置响应类型。

【讨论】:

    猜你喜欢
    • 2015-05-31
    • 2016-12-15
    • 2015-11-17
    • 2018-01-23
    • 1970-01-01
    • 2016-01-02
    • 1970-01-01
    • 2013-12-23
    • 2016-04-24
    相关资源
    最近更新 更多