官术网_书友最值得收藏!

Dynamic select boxes

Frequently on the Internet, you would have come across registration forms where selection of certain fields cause the entire page to refresh in order to show you the details specific to that selection.

An example of that would be countries and cities. It's a natural thing for a web developer to want a person to input the country and city with a select box instead of an input box. This is because cities and countries rarely change, and you really don't want your users making up countries or cities!

However, there are many thousands of cities when you consider the number of countries in the world, and to print them all in a simple registration form is extremely impractical, not to mention their sheer number, as we will see in a later chapter!

Earlier the developers would have come up with a solution like: to add an event watcher, wait for the Country select box to be changed, and when this happened, the entire "state" of the form would be sent to the server and a new page would be generated with the country-specific details added.

Dynamic select boxes

This was a good solution in those times, but these days, we have the luxury of Ajax.

jQuery allows us to very easily check for the country being selected, and replace the Cities select box when the event is triggered. And, the trick to that is so simple, that it's our first example.

Dynamic select boxes

Client-side code

Here's the HTML with the JavaScript embedded in it. I'm going to assume that you've at least used JavaScript before. I'll explain the differences between JavaScript and PHP throughout the book, but the assumption I'm working under is that you're good at PHP, moderate at CSS, and know enough JavaScript to follow along.

In the root of your test web server, place your jquery.min.js file, create a directory, /2-dynamic_select_boxes, and then place the following HTML in it in a file named index.html:

<html>
  <head>
    <script src="/jquery.min.js"></script>
    <script>
      function setup_country_change(){
        // If #country is changed, then call update_cities()
        $('#country').change(update_cities);
      }
    function update_cities(){
      var country=$('#country').attr('value');
      // Call get_cities.php and when retrieved,
      //     call show_cities() with the result.
      $.get('get_cities.php?country='+country, show_cities);
    }
    function show_cities(res){
      // Replace contents of #cities with retrieved result
      $('#cities').html(res);
    }
    // Run setup_country_change() when the document is ready
    $(document).ready(setup_country_change);
    </script>
  </head>
  <body>
    <form>
      <table>
        <tr>
          <th>Country</th>
          <td>
            <select name="country" id="country">
              <option value=""> -- please choose -- </option>
              <option value="ie">Ireland</option>
              <option value="uk">Great Britain</option>
            </select>
          </td>
        </tr>
        <tr>
          <th>cities</th>
          <td id="cities">please choose a country first</td>
        </tr>
      </table>
    </form>
  </body>
</html>

The HTML here is very easy to explain. There is simply a select box for the country, with both the name and the id as country, and there is a placeholder table cell with the ID cities.

The real magic happens with the JavaScript.

How it works

The main function in jQuery is called jQuery. But most people use the common alias $ as it is already set up with the script and is much shorter.

In PHP, the $ symbol indicates that the following string is a variable name, but in JavaScript, $ has no special meaning—it is just another character, which can be used in a variable name. In jQuery's case, $ is an object. Objects and functions are interchangeable in JavaScript. This means that you can call it using parameters like a function, and it will return a value in the form of a jQuery object instance. You can also use it as a static object and call its methods directly.

To start the book, everything will be explained line by line. As the book progresses, less and less will need to be explained, as you will become familiar with how jQuery works.

$(document).ready(setup_country_change);

This line tells the browser to run the setup_country_change function when the document (the main structural element in a web page) is ready for manipulation.

This is a very common pattern, and it is found in most jQuery-powered applications. Almost all jQuery scripts start with a request where jQuery calls a specified function when it is ready to start manipulating the document.

Note that in this case, jQuery is being called as a function, but is then further acted upon as an object. The . character in JavaScript is almost the same as -> in PHP, and indicates either a method or an object variable.

So, to paraphrase the whole discussion, the jQuery function is called with the page document as a parameter. jQuery returns an instance of itself as an object, which is then used to call the ready method with the function reference, setup_country_change.

  function setup_country_change(){
    $('#country').change(update_cities);
  }

This is the function that is called when the document is ready to be manipulated. Note that in PHP, there is no concept of "when"—either things happen now, or don't happen at all. In PHP, things always happen in a straightforward manner—you call a function, and the next line is not processed until that function returns a value.

However, JavaScript is a bit more threaded than that—you can have a process running, which might not return a value for a few seconds; so, sometimes, things happen asynchronously.

This can be quite a leap for a straight PHP developer, so please re-read anything you're not sure of.

When the setup_country_change function is called, jQuery is called with the parameter #country. This parameter is a CSS selector, which indicates an element with the ID country. The change method tells jQuery to set a watch for when the element's value is changed, and when that happens, the update_cities function is to be called.

jQuery is usually called with a parameter. The parameter tells jQuery what it has to act on. The parameter can take many forms. In our examples so far, the form has been a CSS selector; in which case, jQuery is told to perform the following action on all the elements that match that selector. It's important to note that this might be more than one object. For example, $('*') will match every element in your document. Even if there is just one element in question, internally, jQuery will still be thinking in terms of an array.

  function update_cities(){
    var country=$('#country').attr('value');
    $.get('get_cities.php?country='+country, show_cities);
  }

Here's where it gets interesting.

The first line grabs the value of the Country select box. Note that .attr returns the value of the first element, even if more than one is matched.

And $.get is an Ajax call. It tells the client to request data from the server using the first parameter as a URL, and send everything that's returned to the function referenced in the second parameter. The expected data does not need to be in any particular format. In this example, we will expect HTML to be returned by the server.

In PHP, string concatenation is done with the . operator. In JavaScript, it's with +.

  function show_cities(res){
    $('#cities').html(res);
  }

When the server has done its job and echoed out its result for the requested URL, this function then simply pastes the result directly into the selected element as HTML.

Server-side code

We've looked in-depth into the client-side code. You can see from the jQuery for the Country select box that a server-side script needs to be provided, which will read a GET variable for the country and return some HTML, which can then be pasted into the form to complete it.

Here is some example PHP, which will return a select box for Ireland and the UK. Feel free to expand for other countries!

The following code should be saved in a separate file in the same directory as your HTML file. Call this one get_cities.php.

<?php
switch($_REQUEST['country']){
  case 'ie': // { ireland
    $cities=array(
      'Cork', 'Dublin', 'Galway', 'Limerick',
      'Waterford'
    );
    break;
  // }
  case 'uk': // { United Kingdom
    $cities=array(
      'Bath', 'Birmingham', 'Bradford',
      'Brighton &amp; Hove', 'Bristol',
      'Cambridge', 'Canterbury', 'Carlisle',
      'Chester', 'Chichester', 'Coventry',
      'Derby', 'Durham', 'Ely', 'Exeter',
      'Gloucester', 'Hereford', 'Kingston upon Hull',
      /* and on and on! */
      'Newport', 'St David\'s', 'Swansea'
    );
    break;
  // }
  default: // { else
    $cities=false;
  // }
}
if(!$cities)echo 'please choose a country first';
else echo '<select name="city"><option>',
 join('</option><option>',$cities),
 '</select>';
?>

This code looks at the value of $_REQUEST['country'] and returns HTML based on what was requested.

The last three lines show that the returned HTML is a select box. To re-iterate what the demo shows, a select box is provided by the initial HTML, and when it is changed, jQuery sends a message to the PHP, which provides a new select box that jQuery then grafts into the HTML.

Simple, and elegant.

It is worth mentioning that the code that is returned is just HTML. jQuery cannot tell anything from it other than that it is HTML. It would be more useful if the PHP returned the HTML and a status of success or failure, encapsulated in an object or array, and that is what we will do in the next example.

主站蜘蛛池模板: 乾安县| 雷波县| 绥宁县| 彭水| 阳江市| 慈溪市| 周口市| 兴海县| 濉溪县| 新宁县| 望谟县| 宝鸡市| 神木县| 渝中区| 东乡县| 通州市| 应用必备| 尼木县| 炉霍县| 汶上县| 晋宁县| 金湖县| 织金县| 武邑县| 镇赉县| 鸡西市| 泰宁县| 灵璧县| 通榆县| 彰化市| 固镇县| 蓬莱市| 休宁县| 高邮市| 朝阳区| 长寿区| 双流县| 碌曲县| 延川县| 当雄县| 茂名市|