Laravel,如何通过从复选框发送多个值来使用ajax从控制器获取结果

时间:2019-06-17 00:00:15

标签: jquery json ajax laravel

我有一个选择框,它可以正常工作并将值发送到控制器,但我想使用复选框而不是此选择框,并且不使用任何提交按钮,所以这是我需要做的

我尝试使用ajax和复选框,但是当我使用选择框时,我的代码无法获取html数据

     <select class="offer-multiple" style="width: 100%" name="categories[]" id="categories" multiple="multiple">
                                @foreach($categories as $item)
                                    @if(in_array($item->id,$categoryArray))
                                        <option value="{{ $item->id }}" selected="selected">  {{ $item->title }} - {{ $item->num_offer }} Offer</option>
                                    @else
                                        <option value="{{ $item->id }}">   {{ $item->title }} - {{ $item->num_offer }} Offer</option>
                                    @endif
                                @endforeach
                            </select>

jQuery:

$("#categories").change(function() {

//console.log(locationUrl);
var dataArray = [];

var dataString = JSON.stringify($("#categories").val());

var urlCall = '/getOfferCategory/'+locationUrl[5];

console.log(urlCall);

var loadingSection = 'result';
//call ajax
makeAjaxCall(urlCall,dataString,'',loadingSection);
});

1 个答案:

答案 0 :(得分:0)

不确定这是使用复选框的适当方法。如果您使用name []作为名称,则可以使复选框具有相同的名称,以便它向服务器提交数组(仍然是PHP)。

标记如下所示,但是其中包含一个提交按钮。使用复选框选项,您应该如何得知用户何时完成选择?完成选择后,用户将必须单击“提交”按钮或其他内容?

<form action="" method="" class="form" id="form">

    <fieldset>
        <legend>Check Boxes with Same Name</legend>

    <p>
        <label><input type="checkbox" name="category[]" value="1" />1</label>
        <label><input type="checkbox" name="category[]" value="2" /> 2</label>
        <label><input type="checkbox" name="category[]" value="3" /> 3</label>
        <label><input type="checkbox" name="category[]" value="4" /> 4</label>
        <label><input type="checkbox" name="category[]" value="5" /> 5</label>
        <label><input type="checkbox" name="category[]" value="6" /> 6</label>
    </p>

    </fieldset>
    <button type="submit">
    Submit
    </button>

</form>

jQuery类似于:

$("#form").submit(function(e) {

e.preventDefault();

var urlCall = '/getOfferCategory/action';

$.ajax({
    url: "/echo/html/",
    type: "POST",
    dataType:  "HTML",
    data:  $('#form').serialize()
}).done(function (result, status, xhr) {
    alert(result);
}).fail(function (xhr, status, error) {
    alert("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText)
});
});

/ echo / html /用于小提琴。

相关问题