带有ajax和json的Javascript DropDown菜单

这是我的HTML代码


   Select le groupe   

我想在我的代码中使用下拉列表。 在我的代码javascript我有一个function

 function getTable() { $.ajax({ dataType: 'json', type: 'GET', url: 'call/json/mytables', xhrFields: { withCredentials: true }, success: function(response) { console.log(response); sendQuery(response[0]); }, }); } 

像这样,function(响应)给我Json,我需要我的DropDown在onchange =“yyyyy”,但我不知道我怎么能用它????????

您需要从服务器请求下拉列表的数据(您的代码已经在执行此操作),然后根据服务器返回的格式解析响应。 如果我们假设它是JSON格式,那么您可以在响应回调中使用JSON.parse(response) ,否则您将不得不编写一些自定义解析代码。 如果是这种情况,请发表评论,并附上有关您的回复格式的相关信息。

要填充下拉列表,您可以使用$.each迭代数据数组并将元素附加到元素。

这是一个有效的jsFiddle ,下面是更新的代码

 // disable the select control until you get the data $("#groupe").prop('disabled', true); function populateSelectWithOptions($select, data) { // remove any exisiting contents $select.html(''); //iterate over the data and append a select option for each item $.each(data, function(key, val) { $select.append(''); }); // enable the select control $select.prop('disabled', false); } function getTable() { $.ajax({ dataType: 'json', type: 'GET', url: 'call/json/mytables', xhrFields: { withCredentials: true }, success: function(response, status) { console.log(response, status); if (status == "success") { // we expect a response in a JSON format response = JSON.parse(response); // if the response is not in the json format then you will have to // write some custom parsing code here populateSelectWithOptions($("#groupe"), response); } }, }); } // request the data getTable(); 

在下面的代码中, data[i].xdata[i].y (只是一个例子)。它会有所不同,取决于你的json数据。只是一个关于如何处理事情的样本。 将此代码放在您的成功部分中。

  var data=JSON.parse(response);//to parse the json_encoded data for(var i=0;i< data.length;i++) { alldata += ""; } document.getElementById('id').innerHTML = alldata;//for javascript or $("#id").html(alldata);//for jquery