如何将php变量值输入到javascript中

时间:2019-12-18 09:49:37

标签: javascript php laravel foreach laravel-5.8

我想在我的javascript中使用Twig语法创建循环吗?如果是,如何在javascript中访问{{$ t-> name}}

到目前为止,我已经对此进行了测试:

Javascript


var faqs_row = 0;
function addfaqs() {
    html = '<tr id="faqs-row' + faqs_row + '">';
    html += '<td><select class="form-control" name="tim">@foreach ($tim as $t)<option value="{{ $t->id }}">{{ $t->name }}</option>@endforeach</select></td>';
    html += '<td class="mt-10"><button class="badge badge-danger" onclick="$(\'#faqs-row' + faqs_row + '\').remove();"><i class="fa fa-trash"></i> Delete</button></td>';

    html += '</tr>';

    $('#faqs tbody').append(html);

    faqs_row++;
}

查看

<td>
    <select class="form-control" name="tim">
        @foreach ($tim as $t)
            <option value="{{ $t->id }}">{{ $t->name }}</option>
        @endforeach
    </select>
</td>

请帮助我 enter image description here

2 个答案:

答案 0 :(得分:0)

var faqs_row = 0;
function addfaqs() {
html = '<tr id="faqs-row' + faqs_row + '">';
    html += '<td><select class="form-control" name="tim">';
    @foreach ($tim as $t)
        html += '<option value="{{ $t->id }}">{{ $t->name }}</option>';
    @endforeach
    html += '</select></td>';
    html += '<td class="mt-10"><button class="badge badge-danger" onclick="$(\'#faqs-row' + faqs_row + '\').remove();"><i class="fa fa-trash"></i> Delete</button></td>';

    html += '</tr>';

$('#faqs tbody').append(html);

faqs_row++;
}

答案 1 :(得分:0)

为什么不只使用php。我创建了单独的演示。

<?php
    $fruits = ['apple','banana','orange','grape'];
    $options = "";
    foreach ($fruits as $fruit) {
        $options .= "<option>".$fruit."</option>";
    }
?>

<select>
    <?php echo $options?>
</select>

也许这会有所帮助