使用ajax和jquery的下拉列表

我有一些值下拉,如果我改变那些值,那将显示另一个带有来自mysql数据库的下拉列表,通过替换下面的文本首先下拉。我在jsp页面中执行此过程。第二个下拉值当第一个下拉列表发生更改时,来自数据库。我的数据库包含两个表,一个用于country,另一个用于city.country表包含字段countryid和country_name,city表包含字段cityid,countryid和city_name.Below是我的代码我到目前为止。我需要实现ajax和jquery? 你能给我一些fetchCites servlet代码的代码,用于在不使用任何php或.net页面的情况下填充第二个下拉列表。

     JSP Page  function createRequestObject(){ var req; if(window.XMLHttpRequest){ //For Firefox, Safari, Opera req = new XMLHttpRequest(); } else if(window.ActiveXObject){ //For IE 5+ req = new ActiveXObject("Microsoft.XMLHTTP"); } else{ //Error for an old browser alert('Your browser is not IE 5 or higher, or Firefox or Safari or Opera'); } return req; } //Make the XMLHttpRequest Object var http = createRequestObject(); function sendRequest(method, url){ if(method == 'get' || method == 'GET'){ http.open(method,url); http.onreadystatechange = handleResponse; http.send(null); } } function handleResponse(){ if(http.readyState == 4 && http.status == 200){ var response = http.responseText; if(response){ document.getElementById("second_dropdown_code").innerHTML = response; } } } function getCityDropdown() { var w = document.myform.mylist.selectedIndex; var country_id = document.myform.mylist.options[w].value; sendRequest('GET','fetchCites.do?countryid=' + country_id); }    

Hello World!

India England
This text will be replaced by second City dropdown.

在你的编码中尝试这个东西

 

Ajax代码

 $(function() { $('#country').change( function() { var val = $(this).val(); if (val == 223 || val == 224) { $('#othstate').val('').hide(); $.ajax({ url: 'findState.php', dataType: 'html', data: { country : val }, success: function(data) { $('#state').html( data ); } }); } else { $('#state').val('').hide(); $('#othstate').show(); } }); 

假设您要填充给定的状态下拉列表

   

你的json一定是

 [{ "state": "MP" }, { "sate": "UP" }] 

并使用以下代码填充状态下拉列表。 它进行ajax调用并获得响应作为ajax对象,它是一个ajax数组并遍历数组。

  function getStateDropdown() { var w = document.myform.mylist.selectedIndex; var country_id = document.myform.mylist.options[w].value; $.ajax({ url : 'fetchState.do?countryid=' + country_id, success : function(data) { $.each(data, function(i, val) { $("#state").append( ""); }); } }); }