如何通过post方法将数据从ajax传递到laravel 5.2控制器

时间:2016-03-22 19:12:31

标签: javascript php ajax laravel-5.2

Hello StackOverflow系列。这是我的第一个问题,我希望得到帮助。

我是laravel框架的新手,我在我的项目中使用的是5.2版本。 我试图使用post方法从我的ajax函数传递数据到特定的控制器方法,但没有数据传递给控制器​​。

我按照此论坛https://laracasts.com/discuss/channels/laravel/process-data-in-controller-using-ajax-in-laravel中的步骤操作,但无法使其正常运行。这是我到目前为止所做的。

我的JavaScript(post_script.js):

$.ajax({
    method: 'POST',
    url: './home',
    data: {
        userID: 76,
        userName: 'Jimmy'
     },
});

请注意,此文件保存在laravel结构的assets/js目录中。以下是我的路径文件(routes.php)中的内容:

Route::get('/', "MyController@home");
Route::get('home', "MyController@home");

以下是MyController.php文件中的函数:

function home(Request $request) {
    $userID = $request['userID'];
    $userName = $request['userName'];
    return view('home', [
      'userID'=> $userID,
      'userName' => $userName
    ]);
}

在我看来,我试图像这样访问它:

<p>User ID: {{$userID}}</p>
<p>User Name: {{$username}}</p>

什么都没显示!请问我做错了什么?我需要你的帮助。如果我的问题不合适,请原谅我,但我希望你明白我的意思。谢谢

5 个答案:

答案 0 :(得分:8)

您的AJAX正在POST,但您没有设置POST路由,只有GET。添加POST路由,如下所示:

Route::post('home', "MyController@home");

答案 1 :(得分:3)

首先检查您的开发人员/网络工具(例如,firebug),以及您的ajax呼叫是否达到所需的控制器/功能,以及参数是否正确转发。

在Laravel环境中的ajax调用中指定Url的安全方法是使用URL facade,如下所示:

url: "{{ URL::to('home'); }}",

为了做到这一点,你必须将你的js存储为myscript.blade.php(!!)文件,并相应地将它包含在你的视图中。

为了在控制器函数中接收已发布的参数,不需要声明函数参数,只需使用Input :: Get()函数即可。像这样:

public function home()
{
  $userID = Input::Get('userID');
  $userName = Input::Get('userName');
  return view('home', [ 'userID'=> $userID, 'userName' => $userName ]);
}

答案 2 :(得分:1)

如果您尝试执行POST请求,则可能需要CREATE PROCEDURE admfte.cds93_val_deu_sol ( ec_tip_deu CHAR(02), ec_ind_ori_com CHAR, ec_num_ruc LIKE sol_comp.num_ruc_des, ec_num_val LIKE sol_comp.num_doc_des, ec_per_tri LIKE sol_comp.per_tri_des, ec_sem_doc LIKE sol_comp.sem_doc_des, ec_cod_tri LIKE sol_comp.cod_tri_des, ec_cod_dep CHAR(4), ed_fec_sol DATE DEFAULT '01/01/0001' ) RETURNING SMALLINT, CHAR(250), CHAR(8), SMALLINT, CHAR(17), CHAR(6), CHAR(6), CHAR(6), CHAR(6), CHAR, DATE, DATE; {*************************************************************************} DEFINE ls_cod_for LIKE crt.crt_formul; DEFINE lc_num_doc LIKE dbt.dbt_numdoc; DEFINE lc_cod_tri LIKE valores.cod_tri; DEFINE lc_cod_tri_aso LIKE valores.cod_tri_aso; DEFINE lc_cod_tip_doc LIKE valores.cod_tip_doc; DEFINE lc_not_abo CHAR(8); DEFINE ld_fec_ori DATE; DEFINE ld_fec_pre DATE; DEFINE lc_per_doc CHAR(6); DEFINE lc_sem_doc CHAR; DEFINE ls_cod_err SMALLINT; DEFINE lc_msg_err CHAR(250); DEFINE li_count INTEGER; DEFINE lc_num_exp_fra LIKE pre_op_fra.num_doc; DEFINE GLOBAL gc_CodUsu CHAR(08) DEFAULT USER;DEFINE GLOBAL gc_FlgDeb CHAR(01) DEFAULT '0';DEFINE lc_file_log CHAR(100); DEFINE lc_flg_debug CHAR(1); DEFINE lc_flg_explain CHAR(1); DEFINE lc_MsgDebIni VARCHAR(60); DEFINE lc_MsgDebFin VARCHAR(60); SET OPTIMIZATION LOW; IF gc_FlgDeb = '1' THEN SELECT flg_debug, flg_explain INTO lc_flg_debug, lc_flg_explain FROM pbdebugspl WHERE usuario = USER AND nom_spl = "cds93_val_deu_sol"; IF lc_flg_debug = "1" THEN LET lc_file_log = "/tmp/" || USER || "_" || "cds93_val_deu_sol" || ".log"; LET lc_MsgDebIni = "Iniciando ===> " || "cds93_val_deu_sol"; LET lc_MsgDebFin = "Finalizando ===> " || "cds93_val_deu_sol"; SET DEBUG FILE TO lc_file_log; TRACE ON; TRACE lc_MsgDebIni; END IF; IF lc_flg_explain = "1" THEN SET EXPLAIN ON; END IF; ELSE LET lc_flg_debug = '0'; END IF; LET lc_not_abo = "0"; LET ld_fec_ori = '01/01/0001'; LET lc_per_doc = ec_per_tri; LET lc_sem_doc = ec_sem_doc; LET lc_cod_tri = ec_cod_tri; LET lc_cod_tri_aso = "0"; LET lc_cod_tip_doc = "0"; IF ec_tip_deu = "02" THEN -- DDJJ CALL cds93_ver_hay_ops (ec_num_ruc, ec_per_tri, ec_sem_doc, ec_cod_tri) RETURNING ls_cod_err, lc_msg_err; IF ls_cod_err > 0 THEN -- ls cod_err contiene la cantidad de OPs RETURN -24, lc_msg_err, "0", 0, "0", "0", "0", "0", '000101', '0', '01/01/0001', '01/01/0001'; END IF CALL cds91_existe_deb (ec_num_ruc, ec_per_tri, ec_sem_doc, ec_cod_tri, ec_cod_dep) RETURNING ls_cod_err, lc_msg_err, lc_not_abo,ls_cod_for,lc_num_doc,ld_fec_pre; IF ls_cod_err = 1 THEN CALL cds91_fecha_deb (ec_num_ruc, ec_per_tri, ec_sem_doc, ec_cod_tri, ec_cod_dep, ed_fec_sol) RETURNING ls_cod_err, lc_msg_err, lc_not_abo, ls_cod_for, lc_num_doc, ld_fec_ori, ld_fec_pre; LET lc_per_doc = ec_per_tri; LET lc_sem_doc = ec_sem_doc; LET lc_cod_tri = ec_cod_tri; LET lc_cod_tri_aso = '0'; LET lc_cod_tip_doc = '0'; --[2008-000422] : INICIO. SAU20082I020401360] ELSE RETURN ls_cod_err, lc_msg_err, "0", 0, "0", "0", "0", "0", '000101', '0', '01/01/0001', '01/01/0001'; END IF --[2008-000422] : FIN. SAU20082I020401360] ELIF ec_tip_deu = "01" THEN -- VALOR CALL cds93_obt_dat_val (ec_num_val, ec_num_ruc, ec_ind_ori_com) RETURNING ls_cod_err, lc_msg_err, lc_cod_tri, lc_cod_tri_aso, lc_cod_tip_doc, lc_per_doc, lc_sem_doc, ld_fec_ori, ld_fec_pre; IF ls_cod_err < 0 THEN RETURN ls_cod_err, lc_msg_err, "0", 0, "0", "0", "0", "0", '000101', '0', '01/01/0001', '01/01/0001'; END IF LET ls_cod_for = 0; LET lc_num_doc = ec_num_val; {PAS20082A510000808 : INICIO} IF lc_cod_tip_doc = '001004' OR lc_cod_tip_doc = '001005' OR lc_cod_tip_doc = '001007' OR lc_cod_tip_doc = '017004' OR lc_cod_tip_doc = '017504' OR lc_cod_tip_doc = '017604' THEN IF (lc_cod_tip_doc = '001004' OR lc_cod_tip_doc = '001005' OR lc_cod_tip_doc = '001007') THEN SELECT MAX(num_doc) INTO lc_num_exp_fra FROM pre_op_fra WHERE pre_op_fra.num_val = ec_num_val AND ind_est_op = '2' AND ind_gen_op = '3'; IF lc_num_exp_fra IS NOT NULL AND LENGTH(lc_num_exp_fra) > 0 THEN SELECT COUNT(*) INTO li_count FROM pre_op_fra, valores WHERE pre_op_fra.num_val = valores.num_val AND pre_op_fra.num_doc = lc_num_exp_fra AND ind_est_op = '2' AND ind_gen_op IN ( '1', '2' ) AND ind_sal = '1'; IF li_count = 0 THEN RETURN ls_cod_err, lc_msg_err, lc_not_abo, ls_cod_for, lc_num_doc, lc_cod_tri, lc_cod_tri_aso, lc_cod_tip_doc, lc_per_doc, lc_sem_doc, ld_fec_ori, ld_fec_pre; END IF END IF ELSE RETURN ls_cod_err, lc_msg_err, lc_not_abo, ls_cod_for, lc_num_doc, lc_cod_tri, lc_cod_tri_aso, lc_cod_tip_doc, lc_per_doc, lc_sem_doc, ld_fec_ori, ld_fec_pre; END IF END IF {PAS20082A510000808 : FIN} END IF {** Existe restriccion para la compensacion a determiandos tributos **} CALL cds93_val_tributo(lc_cod_tri, 1) RETURNING ls_cod_err, lc_msg_err; IF ls_cod_err < 1 THEN RETURN ls_cod_err, lc_msg_err, "0", 0, "0", "0", "0", "0", '000101', '0', '01/01/0001', '01/01/0001'; END IF RETURN ls_cod_err, lc_msg_err, lc_not_abo, ls_cod_for, lc_num_doc, lc_cod_tri, lc_cod_tri_aso, lc_cod_tip_doc, lc_per_doc, lc_sem_doc, ld_fec_ori, ld_fec_pre; END PROCEDURE

将此添加到meta:

X-CSRF-Token

设置你的AJAX:

<meta name="csrf-token" content="{{ csrf_token() }}">

在Laravel文档中:https://laravel.com/docs/5.2/routing#csrf-x-csrf-token

答案 3 :(得分:0)

首先,你需要像这样设置ajax请求的dataType(如果你使用jQuery)

 $.ajax({
    method: 'POST',
    url: './home',
    dataType: 'json'
    data: {
        userID: 76,
        userName: 'Jimmy'
     },
})

然后尝试使用您的控制器,如下所示

Request::json()

并查看结果

您也可以使用Input :: get():

Request::get('userID')

答案 4 :(得分:0)

您可以使用路线名称将数据传递给控制器​​

 $.ajaxSetup({
            headers:{'X-CSRF-TOKEN': $("meta[name='csrf-token']").attr('content')}
        });
        $.ajax({
            type:'POST',
            url: '{{route("route_name_with_post_method")}}',
            data:{
              'id': data
            },
            success:function(r){

            },error:function(r) {

            }
        });