如何生成还包含并在javascript中运行php代码的HTML代码(onclick事件)

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何生成还包含并在javascript中运行php代码的HTML代码(onclick事件)相关的知识,希望对你有一定的参考价值。

首先,我知道这个问题本身就是一个错误,原因是无法从浏览器运行php,但是我以这种方式询问您如何理解我需要实现的目标。

嗯,我的问题很简单。我得到了一些输入的表格。 (基本上是用于创建食谱的表单(名称,类型,是否为素食者等,以及成分列表)而且我希望用户每次单击按钮时都可以在表单中添加输入。问题是我需要创建的选择输入包含需要运行以获取其内容的php代码,而我显然不能仅仅将我的输入附加到html中。

[我以为我需要使用AJAX,但我从未使用过它,而且在经过数小时的研究后,我无法弄清楚该如何进行,因为我可能未考虑正确的方法。

嗯,我的代码是这样的:

HTML / PHP文件:

    <form>
        // some inputs

        <select name="ingredient1" id="ingredients"> <!-- my select input for the first ingredient -->
            <?php 
            foreach ($ingredients as $ingredient) { ?>
                <option value="<?php echo $ingredient['id']; ?>"><?php echo $ingredient['name']; ?></option>
            <?php } ?>
        </select>

        <div id="add_ingredient_button"></div> <!-- the button with the onclick event -->

    </form>

JS:

    $( document ).ready(function() {

        let ingredientCount = 1

        const addIngredientInput = function () {

            ingredientCount++
            let newSelect = // here let's say I try to concatenate my html and php to get the exact same code than the select input above in the html code plus the right ingredient count to get ingredients2, ingredients3 etc..
            $('#add_ingredient_button').before(newSelect)
            return ingredientCount

            }

        $('#add_ingredient_button').on('click', function(){
            addIngredientInput()
        })

     });

嗯,我知道那可能是超级混乱的,它不能像这样工作,因为php不会由客户端运行,并且显然无论如何它都会以注释或纯文本的形式插入dom,但是我不知道如何生成我在AJAX中输入的代码是什么

很抱歉,但是我对Web开发并不陌生,我可能没有考虑正确的方法

仍然感谢您的时间和回答

答案

如果它始终是具有相同选项的相同select-element,那么您可以简单地克隆select-element。像这样:

HTML / PHP:

<div id="selectors_container">
 <select name="ingredient1" class="ingredients">
  [your PHP code]
 </select>
</div>

JS:

// select the last element by class and get the last child
var item = document.getElementByClass("ingredients").lastChild;
// Copy the element and its child nodes
var clone = item.cloneNode(true);
// Append the cloned element to your container
document.getElementById("selectors_container").appendChild(clone);

更多详细信息,请查看:https://www.w3schools.com/jsref/met_node_clonenode.asp或针对ajax请求:https://www.w3schools.com/js/js_ajax_intro.asp

另一答案

所以我不确定您要做什么。如果您编写PHP,它将在浏览器中转换为html。可以使用Jquery或vanilla检索html。因此,在加载页面并创建html之后,您可以从select / dropdown / input中检索表单值。

我提供的代码使您可以通过按一下按钮来添加新输入,更改选择值,然后打印最终结果。最终结果可以转换为json并通过ajax作为主体参数传递。

let ingredientCount = 0;

$( document ).ready(function() {
      addInputEventListener();
      handleFormCompletion();

     });

const addInputEventListener = () => {
  $('#add-input').click(() => {
    ingredientCount += 1;
    $('#main-form').append(`<input name="ingredient-${ingredientCount}"></input>`)
  })
}

handleFormCompletion = () => {
  let ingredients = {}
  $('#print-ingredients').click(() => {
    ingredients['select'] = $('select[name="ingredients"]').val()
    $('input').each(i => {
      ingredients[$('input').eq(i).attr('name')] = $('input').eq(i).val()
    })
    console.log(ingredients)
    ///ajax post request here
  })
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
  <form id="main-form">
    <select name="ingredients" form="main-form">
      <option value="organic">Organic</option>
      <option value="not organic">Not Organic</option>
      <option value="grapes">Grapes</option>
      <option value="pickles">Pickles</option>
    </select>
   </form>
  <button type="button" id="add-input">add Input</button>
  <button type="button" id="print-ingredients">print Ingredients</button>
</html>

以上是关于如何生成还包含并在javascript中运行php代码的HTML代码(onclick事件)的主要内容,如果未能解决你的问题,请参考以下文章

在 HTML 中请求时使用 PHP 生成 JavaScript 文件

如何在javascript中声明php数组变量并查看数据表

使用包含 php 和 ifs 的 javascript 生成 HTML [关闭]

使用 Maven 生成一个可运行的 jar 并在其中包含库

使用 Javascript 生成包含 JSP 的 HTML

包括:用于单独文件中基本 HTML 和 Javascript 的 SSI 或 PHP