Populating dropdown menus using XMLHTTPREQUEST obj

2019-08-18 06:14发布

问题:

My goal is to have a drop down menu full of US States and upon selecting a State, a second dropdown menu will populate with Cities that are in that State. Since I am not looking to store all of the Cities in my database, I have a PHP file called list-of-cities.php that will store an array of cities from all of the States.

The following code is the JS and HTML which makes the XMLHTTPREQUEST object to request information from list-of-cities.php as well as the dropdown forms. The function AddToOptionsList() adds the value received from the XMLHTTPREQUEST object's responseText (which is a city from the array in list-of-cities.php) to the "cities" dropdown menu.

    function PopulateCities() {

                var statesList = document.frmMain.states;

                var stateValue = statesList[statesList.selectedIndex].value;

                    var i = 0;
                    do {
                    //create new XMLHTTPRequest object
                    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 )
                            {
                            var responseText = xmlhttp.responseText;
                            if( responseText == null){
                                //the request sent a null value from the cities array therefore we reached the end of it
                                break;
                            } else{ 
                               //Add the value received from the response to the "cities" option list
                            AddToOptionList(document.frmMain.cities, i, responseText);
                            }
                            }
                      }
                    xmlhttp.open("GET","http://localhost//wp-content/themes/list-of-cities.php?q="i+stateValue,false);
                    xmlhttp.send();
                    i++;
                    } 
                    while(true);
                }



                function AddToOptionList(OptionList, OptionValue, OptionText) {
                // Add option to the bottom of the list
                OptionList[OptionList.length] = new Option(OptionText, OptionValue);
                }



                <form name="frmMain">
                <div id="choose_state">
                    Select a state from the drop down menu:<select name="states" onChange="PopulateCities();">
                        <option value="choose_state" selected="selected">Choose a state</option>
                        <option value="florida">Florida</option>
                        <option value="newyork">New York</option>
                        <option value="california">Callifornia</option>
                        <option value="northcarolina">North Carolina</option>
                    </select>
                </div><!--choose_state -->

                <select name="cities" >
                <option> Choose a city</option>
                </select>

                </form>

The following is the list-of-cities.php code which currently only has an array for cities in Florida for testing purposes. The $q parameter that is passed from the XMLHTTPREQUEST object is of the form "i + state name" in order to keep track of the position in the cities array.

    <?php
    $florida[]="Gainesville";
    $florida[]="Miami";
    $florida[]="Tampa";
    $florida[]="Orlando";
    $florida[]="Jacksonville";
    $florida[]="Melbourne";
    $florida[]="Tallahassee";

    //$newyork[] = "Manhattan";
    //$newyork[] = "Brooklynn";
    //$newyork[] = "Queens";

    //get the q parameter from URL (i + State name)
    $q=$_GET["q"];

    $i = substr($q,0,1); //first char of $q contains the position in the city array
    $state = substr($q, 1, strlen($q)-1);   //gives the state name from $q
    if( $state == "florida" ) {
       echo $florida[$i];
    }

All of this code together currently works in populating the dropdown menu with all of the 7 cities from the $florida[] array. However, I am currently trying to end the while() loop by waiting for a null value from the cities array which is not working correctly therefore I need help with identifying the size of the $florida[] array in the JS code so that I can end the while() loop and stop populating the dropdown menu.

Any help or tips are much appreciated!

回答1:

Why don't u use jSON and jQuery each?

http://api.jquery.com/jQuery.getJSON/

http://api.jquery.com/jQuery.each/

PHP

<?php
$someArray = array();

$someArray[] = 'value';
$someArray[] = 'value';
$someArray[] = 'value';
$someArray[] = 'value';
$someArray[] = 'value';

echo json_encode($someArray);
?>

jQuery

$.getJSON('http://www.example.com', { state: 'californie' }, function(data) {
    $.each(data, function(index, value){

        alert(index + ' ' + value);
    });
});


回答2:

Whoa. You're working too hard. First, I would recommend jQuery's AJAX function.

Also, it wouldn't hurt to look into JSON for stuff like this. JSON works very well with PHP arrays :)

Basically, you are going to have them select a state, which will send off an ajax request to a php script that will return an array of cities.

So, first just send an AJAX request when they select a state. Next, have php send a JSON array back. Then loop through the JSON array appending it to a new select box. JSON is super easy, so no worries.