简体   繁体   English

在PHP中定义JS函数

[英]Defining a JS function in PHP

I am Working on a little Webpage, which has a .php-include hierarchy. 我正在研究一个小型网页,该网页具有.php-include层次结构。 Now I want to generate two relying Dropdown-Menues, where the second one is updated, after you choose an option in the first one. 现在,我想生成两个依赖的下拉菜单,在第一个菜单中选择一个选项后,第二个菜单将更新。

I would prefer if the code for this page could stay in one file, as I want to achieve this without splitting the code. 我希望此页面的代码可以保留在一个文件中,因为我想在不拆分代码的情况下实现这一目标。

The code looks something like this: 代码看起来像这样:

<?php
echo '<div id="dashheader">
<form action="..." method="get" enctype="text/plain">
<p id="dashheadline">Selbstkosten ermitteln</p>
..
<td><select name="lieferant" onChange="javascript:updateArtikel(this.value);" >
...
<div id="art">
    <select name="artikel">
    <option value="">Erst Lieferanten wählen</option>
    </select>
</div>';
?>

Now i have the Javascript which I want to be executed on a Change in the "lieferant"-Dropdown(Simple Ajax Call): 现在,我有了要在“ lieferant” -Dropdown(简单Ajax调用)中进行更改时执行的Javascript:

<script type="text/javascript">
    function updateArtikel(str) {
        ...
        xmlhttp.onreadystatechange = function() {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById("art").innerHTML = xmlhttp.responseText;
            }
        }
        xmlhttp.open("GET","cure1.php?q="+str,true);
        xmlhttp.send();
        ...
     }
</script>

cure1.php is the same .php-File I generate the Output in. It also contains additional php-Code, in Case it is called with a parameter "q" (see AJAX-Call): curry1.php是我在其中生成输出的.php文件。它还包含其他php代码,以防使用参数“ q”调用它(请参阅AJAX-Call):

if(isset($_GET['q'])){
    echo '<select id="art" name="artikel">';
    $abfrage = //MYSQL-Query; 
    $ergebnis = mysqli_query($con,$abfrage);
    while($row = mysqli_fetch_object($ergebnis))
    {
        echo '<option value = "'.$row->PositionsNr.'" > '.$row->Artikelbezeichnung.'</option>';
    }
    echo '</select>';
}

Now the Question: Is it really possible to leave this code in one File? 现在的问题是:是否真的有可能将此代码保留在一个文件中? If not, How shall I put the code, if the "cure1.php" (my page) is loaded per "index.php?menu=10" ? 如果没有,如果每个“ index.php?menu = 10”加载了“ cure1.php”(我的页面),我该如何放置代码?

see your hierarchy of php file carefully. 仔细查看您的php文件层次结构。 At last code should like 最后代码应该像

<?php 
......
//php code
?>
<html>
    <head>
        <script>
          //javascript code
        </script>
    </head>
</html>

you may also echo all html code within php tags. 您也可以在php标签中回显所有html代码。 This is standard, you may not restricted to do same. 这是标准的,您可能不限于这样做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM