提问者:小点点

有没有方法在javascript动态创建的html输入中添加php变量?


所以我有一个记录,它与另一个命名的结果有一对多的关系,每个结果至少有一个人组成一个团队。

对于团队,我正在动态地创建字段,每个字段中最多有9个人。 为了不混淆团队中每个人属于哪个结果,我传递的是结果ID。

HTML

<button type="button" class="btn add_field_button">
  <i class="fa fa-plus" aria-hidden="true"></i>Add More Fields
</button>

JavaScript

    var max_fields      = 10; //maximum input boxes allowed
    var wrapper         = $(".input_fields_wrap"); //Fields wrapper
    var add_button      = $(".add_field_button"); //Add button ID
    var new_fields      = 19;
    var i = $("")

    var x = 1; //initial text box count
    $(add_button).click(function(e){ //on add input button click
        e.preventDefault();
        if(x < max_fields){ //max input box allowed
            x++; //text box increment
            new_fields++;
            $(wrapper).append('<div class="row"><input type="text" name="outcome[' +new_fields +'][' +x +'][id]" value="<?php echo $outcome->id; ?>" class="form-control" hidden><div class="form-group col-lg-4"><label class="form-control-label text-muted ">*Officer\'s Name:</label><input type="text" name="outcome[' +new_fields +'][' +x +'][officer]" class="form-control" required></div><div class="col-lg-4 form-group-sub"><label class="form-control-label text-muted">*Position:</label><input type="text" name="outcome[' +new_fields +'][' +x +'][position]" class="form-control" required></div><div class="col-lg-3 form-group-sub"><label class="form-control-label text-muted">*Institution Name:</label><select class="form-control" id="institution" name="outcome[' +new_fields +'][' +x +'][institution]" required><option value="">Select Institution</option><option value="option1">First Option</option><option value="option2">Second Option</option><option value="other">Other</option></select></div><a href="#" class="remove_field"><i class="fa fa-times" aria-hidden="true"></i></a></div>');
      //add input box
        }
    });

我试过用双花括号表示变量,但没有用。

样本输出

{"2":{"id":"<?php echo $outcome->id; ?>","officer":"Munthu Oyamba","position":"Ofunika heve","institution":"option1"}},"21":{"3":{"id":"<?php echo $outcome->id; ?>","officer":"Munthu Wachiwiri","position":"Bwantasa","institution":"option2"}}}

共2个答案

匿名用户

Javascript代码在浏览器中执行。 您的浏览器不知道如何执行php代码。 php代码需要在服务器端执行,这意味着在页面被发送到浏览器之前。 向页面动态添加标记什么也不做。

匿名用户

如果您的刀片模板中有javascript,那么它应该可以工作,因为它将字符串(my_var的值)注入到JS块中:

$my_var = 'hi mom!';

<script>
   console.log( {{ $my_var }} );
</script>

如果php变量具有要呈现的标记,则可以使用{!!$my_var!!}

https://laravel.com/docs/7.x/blade#blade-and-javascript-frameworks