javascript - Laravel 5.2 - 在 ajax 请求后从 Controller 返回 View

标签 javascript php ajax laravel laravel-5

我有一个javascript函数,它向 Controller 发送一些要插入表中的信息(主要是数组和id等变量),问题是插入完成后我想使用数据数组返回到不同的 View 我似乎无法做到这一点(我认为这是因为 ajax 请求)

Javascript代码

  $('#importar').submit(function(e) {
       e.preventDefault();
           fdata=preparePostData();
        $.ajax({
            type:'POST',
            url:   $(this).prop('action'), // url, from form
            data:fdata,
            processData: false,
            contentType: false,
            success:function(data) {
                window.location.replace(data.url);
            }
        });
    }); // end form.submit

函数准备PostData()

 var file_data=$('input:file')[0].files;
        var postdata=new FormData();
        postdata.append('_token',token);
        postdata.append('startFrom',startFrom);
        postdata.append('idList',idList);
        postdata.append('nomeCampos',nomeCampos);
        postdata.append('posicaoCampos',posicaoCampos);
        postdata.append('file',file_data[0]);
        return postdata;

Controller 预期代码 最后完成所有插入和功能

  $data = array('listNome' => $listName, 'contacts' => $contacts, 'errors' => $erro);
        return view("XPTO", $data);

最佳答案

您不应该从 ajax 调用返回 View ,因为您会将 View 处理代码作为 ajax 回调的参数。将 ajax 调用视为对服务器的异步“幕后”调用,您可以在其中传递参数并获取其他一些参数

您应该从 Controller 返回一个 JSON 响应,其中包含从 JS 调用路由所需的所有参数,并在 success 回调中解析它。例如:

Controller

//here you should store all the parameters you need in your JS calback
$data = array('status' => 'ok', 'url' => $redirect_url ); 

JS

success:function(data) 
{
    //data will contain the parameters you set in the controller, so you can use them to call the route
    if ( data.status == 'ok' )
         window.location.replace(data.url);
} 

关于javascript - Laravel 5.2 - 在 ajax 请求后从 Controller 返回 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35601503/

相关文章:

javascript - Ajax 404(未找到)循环遍历

php - 如何将php 5.3.8版本更新为php 5.6版本

javascript - 如何使用 Node 的方法覆盖包和 ajax 来覆盖要放置的方法?

javascript - 为什么无法解析此 JSON 对象?

javascript - 返回链式 Promise 的函数的返回类型

javascript - 在 Javascript 中调度大量额外事件的效率如何?

javascript - AngularJS 无法正确路由

java - 客户端无法从服务器接收异常的堆栈跟踪

javascript - jQuery Resizable 不起作用?

Javascript到 "copy in real time"一些字段从一个表单到另一个表单(具有不同的输入名称)