簡體   English   中英

使用PHP幫助在國家/地區使用JS下拉列表

[英]Help using JS dropdown for country/state with PHP

問題出在這里:我有一個針對國家和州的JS下拉列表,該下拉列表以PHP形式運行,供用戶更新其個人資料。

用戶為“美國”選擇國家,然后選擇“科羅拉多州”並提交。 發生的結果是,這些值已確定保存在我的數據庫中,但是在頁面刷新時,只有國家/地區下拉列表隨用戶選擇而保留。 該狀態顯示為“選擇狀態”,盡管值“科羅拉多”位於數據庫中。

我只是無法使PHP和JS互相交談,因此,如果用戶選擇了Colorado,則應從數據庫中將其拉出並在刷新或返回頁面時顯示為選定狀態。

任何想法如何做到這一點? 我嘗試了在JS代碼頂部的建議,但未成功。

這是JS(為簡潔起見,對某些代碼進行了修剪):

// If you have PHP you can set the post values like this
//var postState = '<?= $_POST["state"] ?>';
//var postCountry = '<?= $_POST["country"] ?>';
var postState = '';
var postCountry = '';

// To edit the list, just delete a line or add a line. Order is important.
// The order displayed here is the order it appears on the drop down.
//
var state = '\
US:Alaska:Alaska|\
US:Alabama:Alabama|\
';

var country = '\
US:United States|\
CA:Canada|\
';

function TrimString(sInString) {
  if ( sInString ) {
    sInString = sInString.replace( /^\s+/g, "" );// strip leading
    return sInString.replace( /\s+$/g, "" );// strip trailing
  }
}

// Populates the country selected with the counties from the country list
function populateCountry(defaultCountry) {
  if ( postCountry != '' ) {
    defaultCountry = postCountry;
  }
  var countryLineArray = country.split('|');  // Split into lines
  var selObj = document.getElementById('countrySelect');
  selObj.options[0] = new Option('Select Country','');
  selObj.selectedIndex = 0;
  for (var loop = 0; loop < countryLineArray.length; loop++) {
    lineArray = countryLineArray[loop].split(':');
    countryCode  = TrimString(lineArray[0]);
    countryName  = TrimString(lineArray[1]);
    if ( countryCode != '' ) {
      selObj.options[loop + 1] = new Option(countryName, countryCode);
    }
    if ( defaultCountry == countryCode ) {
      selObj.selectedIndex = loop + 1;
    }
  }
}

function populateState() {

  var selObj = document.getElementById('stateSelect');
  var foundState = false;
  // Empty options just in case new drop down is shorter
  if ( selObj.type == 'select-one' ) {
    for (var i = 0; i < selObj.options.length; i++) {
      selObj.options[i] = null;
    }
    selObj.options.length=null;
    selObj.options[0] = new Option('Select State','');
    selObj.selectedIndex = 0;
  }
  // Populate the drop down with states from the selected country
  var stateLineArray = state.split("|");  // Split into lines
  var optionCntr = 1;
  for (var loop = 0; loop < stateLineArray.length; loop++) {
    lineArray = stateLineArray[loop].split(":");
    countryCode  = TrimString(lineArray[0]);
    stateCode    = TrimString(lineArray[1]);
    stateName    = TrimString(lineArray[2]);
  if (document.getElementById('countrySelect').value == countryCode && countryCode != '' ) {
    // If it's a input element, change it to a select
      if ( selObj.type == 'text' ) {
        parentObj = document.getElementById('stateSelect').parentNode;
        parentObj.removeChild(selObj);
        var inputSel = document.createElement("SELECT");
        inputSel.setAttribute("name","state");
        inputSel.setAttribute("id","stateSelect");
        parentObj.appendChild(inputSel) ;
        selObj = document.getElementById('stateSelect');
        selObj.options[0] = new Option('Select State','');
        selObj.selectedIndex = 0;
      }
      if ( stateCode != '' ) {
        selObj.options[optionCntr] = new Option(stateName, stateCode);
      }
      // See if it's selected from a previous post
      if ( stateCode == postState && countryCode == postCountry ) {
        selObj.selectedIndex = optionCntr;
      }
      foundState = true;
      optionCntr++
    }
  }
  // If the country has no states, change the select to a text box
  if ( ! foundState ) {
    parentObj = document.getElementById('stateSelect').parentNode;
    parentObj.removeChild(selObj);
  // Create the Input Field
    var inputEl = document.createElement("INPUT");
    inputEl.setAttribute("id", "stateSelect");
    inputEl.setAttribute("type", "text");
    inputEl.setAttribute("name", "state");
    inputEl.setAttribute("size", 30);
    inputEl.setAttribute("value", postState);
    parentObj.appendChild(inputEl) ;
  }
}

function initCountry(country) {
  populateCountry(country);
  populateState();
}

這是PHP / HTML(修剪一下):

<?php
include 'dbc.php';
page_protect();

$err = array();
$msg = array();

if ($_POST['doUpdate'] == 'Update') {

    foreach ($_POST as $key => $value) {
        $data[$key] = filter($value);
    }

    $country =          $data['country'];
    $state =            $data['state'];

    mysql_query("UPDATE users SET
    `country` =         '$data[country]',
    `state` =           '$data[state]'

     WHERE id='$_SESSION[user_id]'
    ") or die(mysql_error());

    $msg[] = "Your Profile has been updated";
    //header("Location: mysettings.php?msg=Your new password is updated");

}

$rs_settings = mysql_query("select * from users where id='$_SESSION[user_id]'");
?>

<html>
<body>
    <form name="profile_form" id="profile_form" method="post" action="">
        <?php while ($row_settings = mysql_fetch_array($rs_settings)) {?>
        <input name="doUpdate" type="submit" id="doUpdate" value="Update">

        <table>
            <tr>
                <th>Country:</th>

                <td><select id='countrySelect' name='country' onchange='populateState()'>
                    </select></td>
            </tr>

            <tr>
                <th>State:</th>

                <td>
                    <select id='stateSelect' name='state'>
                    </select> 
                        <script type="text/javascript">
                            initCountry('<?php echo $row_settings['country']; ?>'); 
                    </script>
                </td>
            </tr>
        </table>
    </form>
</body>
</html>

我經常遇到的Javascript問題之一是加載順序。

您似乎正在同時運行並調用populateCountry和populateState,因此一旦確定了國家/地區列表,就沒有太多機會填充“國家/地區”列表。

考慮將“ populateState()”移動到“ populateCountry()”的最后一行,以便在函數處理結束時對其進行調用。

有多種方法可以做到這一點,但這是說明這一點的最簡單方法。

更改頂行

// If you have PHP you can set the post values like this
//var postState = '<?php echo $_POST["state"] ?>';
//var postCountry = '<?php echo $_POST["country"] ?>';
var postState = '';
var postCountry = '';

// If you have PHP you can set the post values like this
var postState = '<?= $_POST["state"] ?>';
var postCountry = '<?= $_POST["country"] ?>';
//var postState = '';
//var postCountry = '';

那行不通嗎?

PHP短標記,即“ <?= ”默認不再啟用,我相信某些較新的php版本。 我已經停止使用它了,我知道它看起來很漂亮,但是如果您遷移到不支持它們的服務器,可能會很痛苦。

暫無
暫無

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

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