【问题标题】:How to get a value from ajax call in laravel如何从 laravel 中的 ajax 调用中获取值
【发布时间】:2016-09-24 15:09:48
【问题描述】:

我想从控制器函数中的 ajax 调用中获取一个值。我该怎么做?

我的代码在这里:

<a  href="javascript:void(0)" onclick="amount_pay('{{ $res->id}}');"><i class="fa fa-pencil-square-o"></i></a>

我的脚本:

<script>

function amount_pay(id) 
         { 
            $.ajax({
            type: 'POST',
            url:  'amount_popup/'+ id,// calling the file  with id

            success: function (data) {
                alert(1);
            }
        });
      } 
</script>

我的路线:

Route::post('amount_popup/{id}', 'AdminController\AmountController@amount_to_pay');

我的控制器功能:

public function amount_to_pay($id)
    {   
        echo $id;
    }

【问题讨论】:

  • 你不能使用刀片内联代替使用
  • 你遇到了什么错误?
  • 我没有收到任何错误。没有从控制器接收到值

标签: ajax laravel laravel-5


【解决方案1】:

轻松返回值:

public function amount_to_pay($id)
{   
    return $id;
}

【讨论】:

    【解决方案2】:

    使用

    var url = '{{ route('amount_popup', ['id' => #id]) }}';
    
    url = url.replace('#id', id);
    

    而不是

    'amount_popup/'+ id
    

    【讨论】:

      【解决方案3】:

      您正试图从 GET 请求中获取值,但您将表单作为 POST 请求发送。

      您应该将脚本代码更改为:

      <script>
      
      function amount_pay(id) 
               { 
                  $.ajax({
                  type: 'GET', //THIS NEEDS TO BE GET
                  url:  'amount_popup/'+ id,// calling the file  with id
      
                  success: function (data) {
                      alert(1);
                  }
              });
            } 
      </script>
      

      然后将您的路线更改为:

      Route::get('amount_popup/{id}', 'AdminController\AmountController@amount_to_pay');
      

      或者如果您想使用 POST... 这样做...

      <script>
      
      function amount_pay(id) 
               { 
                  $.ajax({
                  type: 'POST',
                  url:  'amount_popup',
                  data: "id=" + id + "&_token={{ csrf_token() }}", //laravel checks for the CSRF token in post requests
      
                  success: function (data) {
                      alert(1);
                  }
              });
            } 
      </script>
      

      然后你的路线:

      Route::post('/amount_popup', 'AdminController\AmountController@amount_to_pay');
      

      然后是你的控制器:

      public function amount_to_pay(Request $request)
          {   
              return $request->input('id');
          }
      

      更多信息:

      Laravel 5 Routing

      【讨论】:

        猜你喜欢
        • 2015-09-23
        • 2018-10-21
        • 1970-01-01
        • 1970-01-01
        • 2012-05-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多