Java 如何使用 JSON 数据填充下拉列表作为 jQuery 中的 ajax 响应
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19725203/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to populate dropdownlist with JSON data as ajax response in jQuery
提问by kits
I am working on a j2ee application. In my application I have a drop-down list(or Select element). I want to populate this drop-down list with JSON data as a Ajax response.
我正在开发一个 j2ee 应用程序。在我的应用程序中,我有一个下拉列表(或 Select 元素)。我想用 JSON 数据填充这个下拉列表作为 Ajax 响应。
Below is the code what I have:
下面是我所拥有的代码:
Server side Code (json_source.java) which generates a JSON response. :
生成 JSON 响应的服务器端代码 (json_source.java)。:
package demo.model;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.gson.*;
/**
* Servlet implementation class json_source
*/
public class json_source extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
JsonArray data_json=new JsonArray();
Statement st_loginId=null;
ResultSet rs_loginId=null;
try
{
Connection con=null;
Class.forName("oracle.jdbc.OracleDriver");
/* Connection String for "OPERWH"(exadata) Database */
con=DriverManager.getConnection("jdbc:oracle:thin:*************","*****","*****");
con.setAutoCommit(true);
st_loginId=con.createStatement();
rs_loginId=st_loginId.executeQuery("select login_id \"LOGIN ID\" from user_access");
//System.out.println("entered in frame_login_code");
int login_val=0;
JsonObject json_response=new JsonObject();
while(rs_loginId.next())
{
login_val++;
JsonObject json=new JsonObject();
json.addProperty("value", "login"+login_val);
json.addProperty("text", rs_loginId.getString(1));
data_json.add(json);
}
System.out.println(data_json);
json_response.add("aaData", data_json);
response.setContentType("application/Json");
response.getWriter().write(json_response.toString());
System.out.println(json_response);
}
catch(Exception ex)
{
System.out.println("Exception occured during retrieval of Login_Id in ComboBox :"+ex);
ex.printStackTrace();
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
and the JSON data which successfully generated through above server side code :
以及通过上述服务器端代码成功生成的 JSON 数据:
{
"aaData": [{
"value": "login1",
"text": "kapils"
}, {
"value": "login2",
"text": "davidn"
}, {
"value": "login3",
"text": "alanp"
}]
}
and Below is my Client side code (source1.jsp) which generate ajax request:
下面是我生成ajax请求的客户端代码(source1.jsp):
(Using $.ajax() ) :
(使用 $.ajax() ):
<script type="text/javascript">
$(document).ready(function()
{
$('#id_trial').click(function() {
alert("entered in trial button code");
$.ajax({
type: "GET",
url:"/demo_trial_application/json_source",
dataType: "json",
success: function (data) {
$.each(data.aaData,function(i,data)
{
alert(data.value+":"+data.text);
var div_data="<option value="+data.value+">"+data.text+"</option>";
alert(div_data);
$(div_data).appendTo('#ch_user1');
});
}
});
});
});
</script>
<body>
<div id="div_source1">
<select id="ch_user1" >
<option value="select"></option>
</select>
</div>
<input type="button" id="id_trial" name="btn_trial" value="Trial Button..">
</body>
OR Using ($.getJSON()) :
或使用 ($.getJSON()) :
$.getJSON("/demo_trial_application/json_source", function (data) {
$.each(data.aaData, function (i, data) {
var div_data = "<option value=" + data.value + ">" + data.text + "</option>";
alert(div_data);
$(div_data).appendTo('#ch_user1');
});
});
Now when I clicked on button (#id_trial), the server side code executes successfully and as a result JSON object created. but i am not getting that "JSON response" in callback function of Success parameter using jQuery's ajax call.
现在,当我单击按钮 (#id_trial) 时,服务器端代码成功执行并因此创建了 JSON 对象。但我没有在使用 jQuery 的 ajax 调用的 Success 参数的回调函数中得到“JSON 响应”。
and apart from jQuery's ajax call I also tried with $.getJSON
function to receive JSON response..but I didn't get JSON data.
除了 jQuery 的 ajax 调用,我还尝试使用$.getJSON
函数来接收 JSON 响应......但我没有得到 JSON 数据。
So please tell me if there is any mistake in my code, and how to get JSON data using above code and populate drop-down list.
所以请告诉我我的代码是否有任何错误,以及如何使用上述代码获取 JSON 数据并填充下拉列表。
I want to populate my dropdownlist with JSON data using ajax response.please help me to sort out this problem...its very urgent for my application.
我想使用 ajax 响应用 JSON 数据填充我的下拉列表。请帮我解决这个问题……这对我的申请来说非常紧迫。
采纳答案by rajesh kakawat
try to change the jquery method variable, it might be causing the problem (i.e., you are using the data
variable coming from the ajax callback PLUS are then trying to assign it to the item
object in the jquery method - changed to obj
):
尝试更改 jquery 方法变量,它可能会导致问题(即,您正在使用data
来自 ajax 回调的变量 PLUS 然后尝试将其分配给item
jquery 方法中的对象 - 更改为obj
):
$.ajax({
type: "GET",
url:"/demo_trial_application/json_source",
dataType: "json",
success: function (data) {
$.each(data.aaData,function(i,obj)
{
alert(obj.value+":"+obj.text);
var div_data="<option value="+obj.value+">"+obj.text+"</option>";
alert(div_data);
$(div_data).appendTo('#ch_user1');
});
}
});
});
回答by Pichet Thantipiputpinyo
I use "for"
我用“为”
var List;
jQuery.ajax({
url: "/demo_trial_application/json_source",
type: "POST",
dataType: "json",
async: false,
success: function (data) {
List = data.aaData
$('#ch_user1').empty();
$('#ch_user1').append('<option value="">All</option>');
for (i in List ) {
$('#ch_user1').append('<option value="' + List[i].value + '">' + List[i].text + '</option>');
}
}
});
回答by Tareq Marji
<div class="col-lg-4">
<%--<input type="text" class="form-control" id="txtGender" />--%>
<select class='form-control DropDown' id="txtGender"></select>
</div>
--------------------------------------------------------------------------------
$(document).ready(function () {
$.ajax({
type: "POST",
url: "AjaxCallGrid.asmx/GetDropDown",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (result) {
$('.DropDown').empty();
$('.DropDown').append("<option value='0'>---Select---</option>");
$.each(result.d, function (key, value) {
$('.DropDown').append($("<option></option>").val(value.iD).html(value.firstName));
});
}
});
});
-------------------------------------------------------------------------
[WebMethod]
public List<Students> GetDropDown()
{
DataTable dt = new DataTable();
List<Students> result = new List<Students>();
using (SqlConnection con = new SqlConnection(@"Data Source=DOS-PC\MARJI;Initial Catalog=examples;Integrated Security=True"))
{
using (SqlCommand cmd = new SqlCommand("select id,firstname from Students ", con))
{
con.Open();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
if (dt.Rows.Count > 0)
{
for (int i = 0; i < dt.Rows.Count; i++)
{
result.Add(new Students
{
iD = Convert.ToInt32(dt.Rows[i]["id"].ToString()),
firstName = dt.Rows[i]["firstname"].ToString()
}
);
}
}
return result;
}
}
回答by dush88c
We can populate dropdown like below . it's very easy for you all i guess.
我们可以像下面这样填充下拉列表。我想这对你们来说很容易。
var options = $("#options");
$.getJSON("/Country/GetAll/", function(response) {
$.each(response, function() {
options.append($("<option />").val(this.Id).text(this.Name));
});
});
回答by Xalo Carvalho
Working with Laravel this is my solution:
使用 Laravel 这是我的解决方案:
$("#YOUR_DIV").on("change", function(){
var selected = $(this).val();
makeAjaxRequest(selected);
})
function makeAjaxRequest(opts){
$.ajax({
type: "GET",
url : '{{ action('YOUR_CONTROLLER@YOUR_FUNCTION') }}',
data: { opts: opts },
success: function(data) {
NEW_JS_FUNCTION(data);
}
});
}
function NEW_JS_FUNCTION(params) {
$('#YOUR_DIV').empty();
$('#YOUR_DIV').append('<option value="">ALL</option>');
params.forEach(function(entry){
$('#YOUR_DIV').append('<option value="' + entry.KEY+ '">' + entry.TEXT + '</option>');
});
}
It works. Hope this can help.
有用。希望这能有所帮助。
回答by Jovan MSFT
The simplest way is to download this library https://github.com/JocaPC/jquery-view-engine/tree/master/src. This JQuery library directly loads JSON into dropdows and looks like a perfect match for your example. You just need to put the following code:
最简单的方法是下载这个库https://github.com/JocaPC/jquery-view-engine/tree/master/src。这个 JQuery 库直接将 JSON 加载到 dropdows 中,看起来非常适合您的示例。你只需要输入以下代码:
success: function (data) {
$('#ch_user1').view(data.aaData);
}
Take a look at this page https://jocapc.github.io/jquery-view-engine/docs/ajax-dropdownfor more details.
看看这个页面https://jocapc.github.io/jquery-view-engine/docs/ajax-dropdown了解更多细节。
回答by Nisal Edu
Try as follows
尝试如下
<select id="xxx"></select>
success: function (response) {
for (var i = 0; i < response.length; i++) {
$("#xxx").append("<option value='" + response[i]["id"] + "'>" + response[i]["name"] + "</option>");
}
}