簡體   English   中英

有沒有辦法在 javascript 動態創建的 html 輸入中使用 php 變量?

[英]Is there a way to have a php variable in a javascript dynamically created html input?

所以我有一個與另一個命名結果有一對多關系的記錄,每個結果至少有一個人組成一個團隊。

對於團隊,我動態地創建每個字段最多 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
        }
    });

我已經為變量嘗試了雙大括號,但它不起作用。

樣品 OUTPUT

{"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"}}}

如果您的 Blade 模板中有 javascript,這應該可以工作,因為它將字符串(my_var 的值)注入到 JS 塊中:

$my_var = 'hi mom!';

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

如果您的 php 變量有要呈現的標記,您可以使用{!! $my_var !!} {!! $my_var !!}

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

Javascript 代碼在您的瀏覽器中執行。 您的瀏覽器不知道如何執行 php 代碼。 php 代碼需要在服務器端執行,這意味着在頁面甚至發送到瀏覽器之前。 動態添加<?php?>標記到您的頁面沒有任何作用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM