每个jquery循环laravel数组集合

时间:2017-04-27 05:13:29

标签: php jquery laravel-5.4

我想使用jquery将select标签附加到我的代码中,它的选项需要来自laravel数组集合的值

控制器

$array['skills'] = DB::table('skills')->get();

脚本

 <script type="text/javascript">
    var skill_count=$('#skill_count').val();
    var array = {!!$array['skills']!!};

    $("#add-skill").click(function(){
        skill_count++;            
        var skill='<div class="row skill"><div class="col-sm-4"><label for="name">Skill:</label><select name="skill['+skill_count+'][skill_name]" class="form-control">$.each( array, function( i, val ) {<option value="+ val.id +"> val.skill_name </option>})</select></div><div class="col-sm-4"><label for="name">Experience:</label><select name="skill['+skill_count+'][pivot][experience_year]"   class="form-control">for(i=1;i<=30;i++){<option value="+ i +">i</option>}</select><select name="skill['+skill_count+'][pivot][experience_month]"   class="form-control">for(i=1;i<=12;i++){<option value="+i+">i</option>}</select></div><div class="col-md-12"><a class="skill-remove pull-right">- Remove Skill</a></div></div>'
        $(".show-skill").before(skill);
    });
</script>

但在浏览器中,val.id和val.skill_name没有获取值。

的console.log(val.skill_name);给我价值

2 个答案:

答案 0 :(得分:2)

希望这会有所帮助

var array =  [{
    id: 2,
    skill_name: 'abc'
}, {
    id: 3,
    skill_name: 'xyz'
}];

var options;
$.each( array, function( key, value ) {
console.log(value.skill_name);
  options = options + '<option value="'+value.id+'">'+value.skill_name+'</option>';
});


var skillhtml = '<div><label for="name">Skill:</label><select name="skillname">'+options+'</select></div>';

$("#container").html(skillhtml);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="container">
</div>

jsfiddle:https://jsfiddle.net/j5nkLabw/

答案 1 :(得分:1)

因为你需要echo php数组,所以在使用之前json_encode

var array = {!!json_encode($array['skills'])!!};或更好地在控制器中对其进行编码,

$jsonArray = json_encode($array['skills']);

然后在你的脚本中使用它 var array = {!! $jsonArray!!}