Reputation: 1
I want to call a jsp file to return a json object to my ajax call. is it possible? if it is possible, could you please share some example code of both the jsp file and jquery ajax code? Thanks in advance.
Upvotes: 0
Views: 1601
Reputation: 8197
Lots and lots of example is in web , guess you are Little lazy in searching let me share an example, And i am using a servlet for the server side
Create a bean,
public class Countries {
public Countries(String code,String name)
{
this.setCode(code);
this.setName(name);
}
public Countries() {}
private String code;
private String name;
public void setCode(String code) {
this.code = code;
}
public String getCode() {
return code;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
And DAO class to add the data from the database or even hardcode the data,
ArrayList<Countries> countryList = new ArrayList<Countries>();
while(rs.next()) {
Countries country=new Countries();
country.setCode(rs.getString("Code"));
country.setName(rs.getString("Name"));
countryList.add(country);
}
After that create a servlet , which gets the data from the DAO and sends it to the JSP ,
ArrayList<Countries> country=new ArrayList<Countries>();
country=FetchData.getAllCountries();
Gson gson = new Gson();
JsonElement element = gson.toJsonTree(country, new TypeToken<List<Countries>>() {}.getType());
JsonArray jsonArray = element.getAsJsonArray();
response.setContentType("application/json");
response.getWriter().print(jsonArray);
}
And finally a JSP to view ,
<script type="text/javascript">
$(document).ready(function() {
$("#tablediv").hide();
$("#showTable").click(function(event){
$.get('PopulateTable',function(responseJson) {
if(responseJson!=null){
$("#countrytable").find("tr:gt(0)").remove();
var table1 = $("#countrytable");
$.each(responseJson, function(key,value) {
var rowNew = $("<tr><td></td><td></td></tr>");
rowNew.children().eq(0).text(value['code']);
rowNew.children().eq(1).text(value['name']);
});
}
});
$("#tablediv").show();
});
});
</script>
<input type="button" value="Show Table" id="showTable"/>
<div id="tablediv">
<table cellspacing="0" id="countrytable">
<tr>
<th scope="col">Code</th>
<th scope="col">Name</th>
</tr>
</table>
</div>
Hope it helps !!
Upvotes: 1