如何从laravel中的ajax调用中获取值

时间:2016-05-26 14:30:27

标签: ajax laravel laravel-5

我想从控制器函数中的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;
    }

3 个答案:

答案 0 :(得分:0)

轻松返回值:

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

答案 1 :(得分:0)

使用

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

url = url.replace('#id', id);

而不是

'amount_popup/'+ id

答案 2 :(得分:0)

您正在尝试从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