Populate second dropdown using jQuery & Ajax

2019-05-25 21:25发布

问题:

I am trying to populate a second dropdown list based on the value of the first dropdown from an external html file which is only filled with the options.

Example of external file:

<option value="Bedfordshire">Bedfordshire</option>
<option value="Berkshire">Berkshire</option>
<option value="Buckinghamshire">Buckinghamshire</option>

Example of first dropdown values:

 <select>
 <option value="GB">UNITED KINGDOM</option> //option to load drop-GB.html
 <option value="US">UNITED STATES</option> //option to load drop-US.html
</select>

It all works fine in FF/Safari/Chrome but not at all in IE or iPad?

var $shipcountry = $('#ShippingCountry');
 $ShippingStateSelect = $('#ShippingStateSelect');
   $ShippingStateSelect.load('drop-GB.html'); //pre load default list

  $shipcountry.change(function () {
    var countryName = $shipcountry.val();

        $.ajax({
            type: 'GET',
            url: 'drop-' + countryName + '.html',
            success: function (msg) {       
                $ShippingStateSelect.load('drop-' + countryName + '.html');
        //fire other events on page
            },
            error: function (msg) {
               $ShippingStateSelect.hide();
        //show error message here
            },

        }); 

  });

回答1:

You are not sorting you incoming HTML, and since it isnt "pure" elements IE fails while Firefox/Chrome etc tries to fix it.

Your drop-US.html contains HTML structure like

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<!-- BC_OBNW -->
<head>
<title>drop-US</title>
<link href="/StyleSheets/ModuleStyleSheets.css" type="text/css" rel="StyleSheet" />
<script type="text/javascript">var jslang='EN';</script>
</head>

Which it then tries to insert into the selectbox.

So you should either filter it out in the ajax request, or remove it in the source. :)