所以我想制作烹饪食谱搜索系统。用户可以选择配料中的成分,也可以选择不应该在配方中的成分。我有2个下拉菜单,用户选择该成分,并通过javascript显示在屏幕上。因此,在用户选择所有成分后,他按下“搜索”,我的控制器应该接收所有选择的成分和不需要的成分,所以我可以进行查询。这是我的观点:
@extends('layouts.app')
<style>
</style>
@section('content')
<h5 align="center">Main Page</h5>
<br>
<div align="center">
<div style="display: inline-block;text-align: left;">
Choose ingredient
<br><br>
<select name="ingredient" id="ingredient" class="form control">
<option value="0">Choose...</option>
@foreach ($ingredients as $ingredient)
<option value="{{ $ingredient->id }}">{{ $ingredient->name }}</option>
@endforeach
</select>
<input type="button" id="button1" value="+ Add ingredient" onclick="addIngredient();"></input>
<br><br>
<div id="Chosen_ingredients"></div>
<br>
Choose ingredients, which should not be in the recipe
<br><br>
<select name="ingredient2" id="ingredient2" class="form control">
<option value="0">Choose...</option>
@foreach ($ingredients as $ingredient)
<option value='{{ $ingredient->id }}'>{{ $ingredient->name }}</option>
@endforeach
</select>
<input type="button" id="button2" value="+ Add ingredient" onclick="addUnwantedIngredient();"></input>
<br><br>
<div id="Unwanted_ingredients"></div>
<button class="btn btn-primary" onclick="location.href='{{ url('foundrecipes') }}'">Search</button>
<script>
var x = 1;
var array = Array();
var ing = Array();
function addIngredient()
{
array[x] = document.getElementById("ingredient").selectedIndex;
if(array[x] > 0)
{
ing[x] = $("select[name='ingredient'").find('option:selected').text();
x++;
var e = "";
for (var y=1; y<array.length; y++)
{
e += y + " . " + " " + ing[y] + "<br/>";
}
document.getElementById("Chosen_ingredients").innerHTML = e + "<br/>";
return array;
}
else
{
alert('Choose ingredient from the list');
}
}
var z = 1;
var array2 = Array();
var ing2 = Array();
function addUnwantedIngredient()
{
array2[z] = document.getElementById("ingredient2").selectedIndex;
if(array2[z] > 0)
{
ing2[z] = $("select[name='ingredient2'").find('option:selected').text();
z++;
var e = "";
for (var y=1; y<array2.length; y++)
{
e += y + " . " + " " + ing2[y] + "<br/>";
}
document.getElementById("Unwanted_ingredients").innerHTML = e + "<br/>";
return array2;
}
else
{
alert('Choose ingredients from the list');
}
}
</script>
</div>
@endsection
如何将这两个数组传递给我的控制器并从中进行查询?
答案 0 :(得分:0)
您可以为每个数组使用隐藏输入,并在向数组添加项目时更新值。并使用分隔符分隔每个值。 我的意思是你可以有两个文本输入:
<input type="hidden" name="array1" id="array1" />
<input type="hidden" name="array2" id="array2" />
并更新这些值:
$('#ingredient').on('change',function () {
array1.push($(this).val())
$('#array1').val(array1.join('-')); "-" is your seperator
});
也为array2做。
在后端,您可以使用$array1 = explode('-', $array1);
将文本数据转换为数组。