简体   繁体   English

HTML 表单 - 需要 js/php 组合功能

[英]HTML forms - need a js/php combo capability

I have two dropdown lists.我有两个下拉列表。 Both are to be filled by PHP via a mysql query.两者都由 PHP 通过 mysql 查询填充。 My problem is I want the form to be responsive if these list selections change.我的问题是,如果这些列表选择发生变化,我希望表单能够响应。 For instance, I need to populate the second list via another query based upon the selection of the first list.例如,我需要根据第一个列表的选择通过另一个查询填充第二个列表。

Problem is: I need "on_change" to POST the form data AND to trigger PHP instead of Javascript.问题是:我需要“on_change”来发布表单数据并触发 PHP 而不是 Javascript。 Is there a way to collect that selection in Javascript and then send it to PHP and then refill the form?有没有办法在 Javascript 中收集该选择,然后将其发送到 PHP,然后重新填写表单? Hope I'm making myself clear.希望我说清楚。 Thanks,谢谢,

Dana达娜

Use Javascript to detect a change of the list.使用 Javascript 检测列表的更改。 When a change occurs, you can make an AJAX request using a PHP script to return a new list.发生更改时,您可以使用 PHP 脚本发出 AJAX 请求以返回新列表。 Javascript can manipulate the new data set and replace the DOM with the new appropriate list. Javascript 可以操作新数据集并用新的适当列表替换 DOM。

<script type=\"text/javascript\">
            function changeCountry(){
                var e = document.getElementById(\"country_id\");
                var country_id = e.options[e.selectedIndex].value;
                if(country_id == 1){
                    // Display states
                    document.getElementById('display_province').style.display = \"none\";
                    document.getElementById('display_state').style.display = \"\";
                    document.getElementById('display_state').style.visibility = \"visible\";
                }
                else{
                    // Display Province
                    document.getElementById('display_state').style.display = \"none\";
                    document.getElementById('display_province').style.display = \"\";
                    document.getElementById('display_province').style.visibility = \"visible\";
                    // Remove current selection list 
                    var select = document.getElementById('province_id');
                    for (var option in select){
                        select.remove(option);
                    }
                    // Get Provinces for country_id
                    var xmlhttp = new XMLHttpRequest();
                    // Include fix for IE6 and IE5
                    if (window.XMLHttpRequest) {
                        // code for IE7+, Firefox, Chrome, Opera, Safari
                        xmlhttp = new XMLHttpRequest();
                    } else {
                        // code for IE6, IE5
                        xmlhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");
                    }
                    xmlhttp.onreadystatechange = function() {
                        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                            var xmlDoc = xmlhttp.responseXML;
                            // get each property
                            var x=xmlDoc.getElementsByTagName('province');
                            for (i=0;i<x.length;i++)
                            { 
                                var e = document.getElementById('province_id');
                                var opt = document.createElement('option');
                                opt.value = x[i].getElementsByTagName('zoneid')[0].textContent;
                                opt.innerHTML = x[i].getElementsByTagName('zone')[0].textContent;
                                e.appendChild(opt);
                            }
                        }
                    }
                    var url = 'get_provinces.php?country_id='+country_id;
                    // var url = 'provinces.xml';
                    xmlhttp.open('GET',url,false);
                    xmlhttp.setRequestHeader(\"Content-type\", \"text/xml\");
                    xmlhttp.send();
                }
            }
            function changeShippingCountry(){
                var e = document.getElementById(\"shipto_country_id\");
                var shipto_country_id = e.options[e.selectedIndex].value;
                if(shipto_country_id == 1){
                    // Display states
                    document.getElementById('shipto_display_province').style.display = \"none\";
                    document.getElementById('shipto_display_state').style.display = \"\";
                    document.getElementById('shipto_display_state').style.visibility = \"visible\";
                }
                else{
                    // Display Province
                    document.getElementById('shipto_display_state').style.display = \"none\";
                    document.getElementById('shipto_display_province').style.display = \"\";
                    document.getElementById('shipto_display_province').style.visibility = \"visible\";
                    // Remove current selection list 
                    var select = document.getElementById('shipto_province_id');
                    for (var option in select){
                        select.remove(option);
                    }
                    // Get Provinces for country_id
                    var xmlhttp = new XMLHttpRequest();
                    // Include fix for IE6 and IE5
                    if (window.XMLHttpRequest) {
                        // code for IE7+, Firefox, Chrome, Opera, Safari
                        xmlhttp = new XMLHttpRequest();
                    } else {
                        // code for IE6, IE5
                        xmlhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");
                    }
                    xmlhttp.onreadystatechange = function() {
                        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                            var xmlDoc = xmlhttp.responseXML;
                            // get each property
                            var x=xmlDoc.getElementsByTagName('province');
                            for (i=0;i<x.length;i++)
                            { 
                                var e = document.getElementById('shipto_province_id');
                                var opt = document.createElement('option');
                                opt.value = x[i].getElementsByTagName('zoneid')[0].textContent;
                                opt.innerHTML = x[i].getElementsByTagName('zone')[0].textContent;
                                e.appendChild(opt);
                            }
                        }
                    }
                    var url = 'get_provinces.php?country_id='+shipto_country_id;
                    // var url = 'provinces.xml';
                    xmlhttp.open('GET',url,false);
                    xmlhttp.setRequestHeader(\"Content-type\", \"text/xml\");
                    xmlhttp.send();
                }
            }
            function addProvince(){
                // Get input
                var np = document.getElementById('new_province').value;
                // Get country_id
                var e = document.getElementById(\"country_id\");
                var country_id = e.options[e.selectedIndex].value;
                // Erase input
                document.getElementById('new_province').value = \"\";
                // Add to database
                var xmlhttp = new XMLHttpRequest();
                // Include fix for IE6 and IE5
                if (window.XMLHttpRequest) {
                    // code for IE7+, Firefox, Chrome, Opera, Safari
                    xmlhttp = new XMLHttpRequest();
                } else {
                    // code for IE6, IE5
                    xmlhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");
                }
                xmlhttp.onreadystatechange = function() {
                    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                        var xmlDoc = xmlhttp.responseXML;
                    }
                }
                var url = 'add_provinces.php?province='+np+'&country_id='+country_id;
                xmlhttp.open('GET',url,false);
                xmlhttp.setRequestHeader(\"Content-type\", \"text/xml\");
                xmlhttp.send();
                changeCountry();
                changeShippingCountry();
            }
            function addShippingProvince(){
                // Get input
                var np = document.getElementById('shipto_new_province').value;
                // Get country_id
                var e = document.getElementById(\"shipto_country_id\");
                var country_id = e.options[e.selectedIndex].value;
                // Erase input
                document.getElementById('shipto_new_province').value = \"\";
                // Add to database
                var xmlhttp = new XMLHttpRequest();
                // Include fix for IE6 and IE5
                if (window.XMLHttpRequest) {
                    // code for IE7+, Firefox, Chrome, Opera, Safari
                    xmlhttp = new XMLHttpRequest();
                } else {
                    // code for IE6, IE5
                    xmlhttp = new ActiveXObject(\"Microsoft.XMLHTTP\");
                }
                xmlhttp.onreadystatechange = function() {
                    if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                        var xmlDoc = xmlhttp.responseXML;
                    }
                }
                var url = 'add_provinces.php?province='+np+'&country_id='+country_id;
                xmlhttp.open('GET',url,false);
                xmlhttp.setRequestHeader(\"Content-type\", \"text/xml\");
                xmlhttp.send();
                changeShippingCountry();
                changeCountry();                
            }
            function hideShipping(){
                    document.getElementById('shipping').style.display = \"none\";
                    document.getElementById('shipping').style.visibility = \"hidden\";
            }
            function displayShipping(){
                    document.getElementById('shipping').style.display = \"\";
                    document.getElementById('shipping').style.visibility = \"visible\";
            }

You can make an ajax call to an endpoint you set up that runs some php code and returns some JSON that your javascript can then use to populate the second list.您可以对您设置的端点进行 ajax 调用,该端点运行一些 php 代码并返回一些 JSON,然后您的 javascript 可以使用这些 JSON 来填充第二个列表。 Your javascript would look something like:你的javascript看起来像:

$.ajax( "your-endpoint.php" )
  .done(function(data) {
    // use javascript to dynamically populate your list
    var json = data;
    //assuming data is a list you could iterate over it
    $.each(data, function (k, v) {
      //use this to populate your list
    }
  })
  .fail(function() {
    // show an error message on your form
  });

Your PHP endpoint would have to return a JSON object so that your javascript can more easily use it.您的 PHP 端点必须返回一个 JSON 对象,以便您的 javascript 可以更轻松地使用它。

Communcation betwen php and javascript is typically done by Ajax, which is very simple to use in jQuery. php 和 javascript 之间的通信通常由 Ajax 完成,在 jQuery 中使用起来非常简单。 The basic syntax is something like this:基本语法是这样的:

$.ajax({
    type: "POST",
    url: "yourFile.php",
    data: "{data: " + yourData + "}", //yourData is javascript variable 
    success: function(result){
        //do something with result from php file
    }
});

Where variable yourData is what you want to send to php script and it would be accessible throught $_POST['data'].其中变量 yourData 是您要发送到 php 脚本的内容,并且可以通过 $_POST['data'] 访问它。

Everyone answered that Ajax is the solution, and I agree, Ajax is more elegant, but Ajax is not the only solution.每个人都回答说 Ajax 是解决方案,我同意,Ajax 更优雅,但 Ajax 不是唯一的解决方案。 I post this answer only to show another way to do it : without Ajax.我发布这个答案只是为了展示另一种方法:没有 Ajax。

The first code ( combos.php ) is the page with a combo that, when selected, calls PHP.第一个代码( combos.php )是具有组合的页面,选中时调用PHP。 The second code ( combos_action.php ) is the PHP that returns the values according to the option selected.第二个代码 ( combos_action.php ) 是根据所选选项返回值的 PHP。 To make this codes to work, create two text files with the given names, copy-paste the codes and run it from your browser with http://localhost/combos.php .要使此代码起作用,请创建两个具有给定名称的文本文件,复制粘贴代码并从浏览器中使用http://localhost/combos.php运行它。 If you change the filenames, change them in the code, also.如果更改文件名,也要在代码中更改它们。

Here is how it works : the page shows a simple combo filled with the days of the week.这是它的工作原理:该页面显示了一个简单的组合,其中包含一周中的几天。 When a day is selected the JavaScript's onchange event fires and the form is autosubmitted, PHP gets the selected day and stores some values in session, returns to the page that refreshes and fills the second combo with those values.选择一天后,JavaScript 的onchange事件将触发并自动提交表单,PHP 获取所选日期并在会话中存储一些值,然后返回刷新页面并用这些值填充第二个组合。 Comments will help you to understand:评论将帮助您理解:

combos.php组合.php

<?php
session_start(); // NECESSARY TO RETRIEVE THE VALUE RETURNED FROM PHP.
?>
<html>
  <head>
    <title>By José Manuel Abarca Rodríguez</title>
    <script type="text/javascript">

// AUTOSUBMIT FORM #1 WHEN ANY OPTION IN COMBO #1 IS SELECTED.
function combo1_selected () {
document.getElementById( "form1" ).submit();
}
    </script>
  </head>
  <body>
<!-- THIS IS COMBO #1. -->
    <form id="form1" method="post" action="combos_action.php">
      Select a day
      <br/>
      <select name="combo1" onchange="combo1_selected()"> <!-- NOTICE THE EVENT! -->
        <option>Monday</option>
        <option>Tuesday</option>
        <option>Wednesday</option>
      </select>
    </form>
<?php
// DISPLAY COMBO #2 ONLY IF COMBO #1 WAS SELECTED.
if ( isset( $_SESSION[ "combo2" ] ) )
   { echo "<br/>" .
          "<br/>" .
          "Options for <b>" . $_SESSION[ "combo1" ] . "</b>" .
          "<br/>" .
          "<select name='combo2'>";
     // SEPARATE THE OPTIONS RETURNED FROM PHP.
       $options = explode( ",",$_SESSION[ "combo2" ] );
     // DISPLAY THE OPTIONS FOR THE COMBO.
       for ( $i = 0; $i < count( $options ); $i++ )
         echo "<option>" . $options[ $i ] . "</option>";
     echo "</select>";
   }
?>
  </body>
</html>

combos_action.php组合动作.php

<?php
session_start();
$_SESSION[ "combo1" ] = $_POST[ "combo1" ]; // SELECTED OPTION.

if ( $_SESSION[ "combo1" ] == "Monday" )
   $_SESSION[ "combo2" ] = "mon 1,mon 2,mon 3"; // RETURN THESE VALUES.

if ( $_SESSION[ "combo1" ] == "Tuesday" )
   $_SESSION[ "combo2" ] = "tue 1,tue 2,tue 3"; // RETURN THESE VALUES.

if ( $_SESSION[ "combo1" ] == "Wednesday" )
   $_SESSION[ "combo2" ] = "wed 1,wed 2,wed 3"; // RETURN THESE VALUES.

header( "Location: combos.php" ); // RETURN TO PAGE.
?>

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

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