Laravel中Ajax Post请求中缺少参数 [英] Missing params in Ajax Post request in Laravel

查看:278
本文介绍了Laravel中Ajax Post请求中缺少参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试发出Ajax发布请求并传递参数以在查询中使用它们,但是我的参数始终为空.这是我的代码:

I am trying to make an Ajax post request and pass params to use them in a query, but my params are always empty. Here is my code:

$.ajaxSetup({
    headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
});

function searchPatient(){
    var params = {
        'name'      : $("#input-search-name").val(),
        'lastname'  : $("#input-search-lastname").val() 
    }
    console.log($('meta[name="csrf-token"]').attr('content'));
    $.ajax({
        data        :  params,
        url         : '{{ route("searchPatient") }}',
        contentType: "application/json",
        type        : 'post',
        beforeSend  : function(){
            console.log(params);
        },
        success     : function(data){
            //Inserto a la tabla principal el contenido
            $("#main-table-patients").html(data);
            //alert('exito');
        },
        error       : function(xhr, status, error) {
              var err = eval("(" + xhr.responseText + ")");
              console.error(err.Message);
        }
    });
}

这是我的web.php

And this is my web.php

Route::group(['middleware'=>'auth'], function(){
  Route::namespace('Patient')->group(function(){
    Route::resource('/patients','PatientController');
    Route::post('/patients/search/{name?}/{lastname?}','PatientController@search')->name('searchPatient');
  });
});

这是我在控制器中的方法

And this is my method in my controller

public function search($name = '', $lastname = '')
{
  $patients = '';
  $patients = Patient::where('name', 'like', '%'.$name.'%')
      ->Where('lastName','like','%'.$lastname.'%');

  return $name.' and '.$lastname;   
}

推荐答案

这是预期的行为.您正在POST中发送变量,但是您的路由旨在从url中检索变量. 决定你想要... 如果您想在POST中传递它们,那么您的Ajax调用网址应为/patients/search 并且您的路线应该只有

It's an expected behaviour. You are sending in POST the variables but your route is designed to retrive the variables from the url. Decide what you want ... if you want to pass them in POST then your ajax call's url should be /patients/search and your route should be only

Route::post('/patients/search','PatientController@search');

您的控制器此时可以处理$ request对象

your controller at that point can deal with $request object

public function search(Illuminate\Http\Request $request) {
    dd($request->all());
}

如果您想在url中传递它们(不是个好主意,恕我直言) 然后将您的Ajax调用网址更改为:

if you want to pass them in the url (not a good idea IMHO) then change your ajax call url to:

url: '/patients/search/' + params.name + "/" + params.lastname

如果两个参数之一包含斜线"(/),则此方法可能会导致问题

This approach can cause problems in case one of the 2 params contains a "slash" (/)

这篇关于Laravel中Ajax Post请求中缺少参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆