【问题标题】:How to pass two value to controller method using ajax in Laravel如何在 Laravel 中使用 ajax 将两个值传递给控制器​​方法
【发布时间】:2014-06-20 01:06:15
【问题描述】:

我有两个选择框。首先,我选择选择框 1 值。然后我选择选择框 2 值。当我选择选择框 2 时,我尝试使用 ajax 将选择框 1 和 2 的值传递给控制器​​方法。我只能传递一个值。如何传递两个值。

选择框 1

            @foreach($routes as $route)
            <option name = 'origin' value='{{$route->rte_origin}}'>{{$route->rte_origin}}</option>
            @endforeach

选择框 2

{{ Form::select('destination', array(), null, array('class' => 'large', 'id'=>'destination')) }}        

还有我的 ajax 代码:

<script type="text/javascript">
$(document).ready(function($){    
  $('#destination').change(function(){
    var destination= $(this).find(':selected').text();

    $.get("{{ URL::route('getDate')}}", 
      {destination: destination},
      function(data) {
        var model = $('#ja');
        model.empty(); 
        $.each(data, function(index, element) {
                  ................
            });
      });
  });
});

【问题讨论】:

    标签: php ajax laravel controller return-value


    【解决方案1】:

    分别选择它们(按 id):

    var origin = $(this).find('#origin').text();
    var destination = $(this).find('#destination').text();
    

    这是您传递的数据:

    {destination: destination},
    

    您现在可以更改它以传递更多项目:

    {origin: origin, destination: destination},
    

    【讨论】:

    • 这不是一个完成的代码,这是一个你可以做什么的想法。例如,如果您不在 HTML 选择中设置 ID,它将不起作用。
    【解决方案2】:

    {destination: destination} 周围的花括号表示它是一个数组,因此您可以添加任意数量的值,并用逗号分隔。例如

    {key1:value1, key2:value3, key3:value3}
    

    此外,您可能有兴趣知道 $.get 函数只是完整 ajax 函数的快捷方式,它提供了更多功能,例如:

    $.ajax({
        url: "path/to.resource",
        type: "GET", //can be any HTTP VERB, eg GET,POST,PUT,DELETE etc...
        data:{data1:value1, data2:value2}, //any data you want to pass to the function
        async: true, //make call synchronous or asynchronous
        dataType:'json', //type of response you are expecting from server eg, text, json etc...
        success: function (data) {
            //code to run on successfully return. any returned data is contained in the data variable
        },
        error: function (xhr, ajaxOptions, thrownError) {
            //code to run in the event of an error
        },
    });
    

    jquery ajax 函数的完整使用细节可以在这里找到:https://api.jquery.com/jQuery.ajax/

    【讨论】:

      猜你喜欢
      • 2018-01-25
      • 2014-12-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多