JSON: JavaScript Object Notation.
JSON is syntax for storing and exchanging text information. Much like XML.
JSON is smaller than XML, and faster and easier to parse.
First Create simple jsp page in netbeans:
index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>AJAX calls to Servlet using JQuery and JSON</title> <script src="http://code.jquery.com/jquery-latest.min.js"></script>1:
2: <script>
3: $(document).ready(function() {4: $('#country').change(function(event) {5: var $country=$("select#country").val();6: $.get('ActionServlet',{countryname:$country},function(responseJson) {7: var $select = $('#states');8: $select.find('option').remove();9: $.each(responseJson, function(key, value) {10: $('<option>').val(key).text(value).appendTo($select);11: });
12: });
13: });
14: });
</script> </head> <body> <h1>AJAX calls to Servlet using JQuery and JSON</h1> Select Country: <select id="country"> <option>Select Country</option> <option value="India">India</option> <option value="US">US</option> </select> <br/> <br/> Enter: <select id="states"> <option>Select State</option> </select> </body> </html>
ActionServlet.java
package ajaxdemo; import com.google.gson.Gson; import java.io.IOException; import java.io.PrintWriter; import java.util.*; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class ActionServlet extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { String country=request.getParameter("countryname"); Map<String, String> ind = new LinkedHashMap<String, String>(); ind.put("1", "New delhi"); ind.put("2", "Tamil Nadu"); ind.put("3", "Kerala"); ind.put("4", "Andhra Pradesh"); Map<String, String> us = new LinkedHashMap<String, String>(); us.put("1", "Washington"); us.put("2", "California"); us.put("3", "Florida"); us.put("4", "New York"); String json = null ; if(country.equals("India")){ json= new Gson().toJson(ind); } else if(country.equals("US")){ json=new Gson().toJson(us); } response.setContentType("application/json"); response.setCharacterEncoding("UTF-8"); response.getWriter().write(json); } finally { out.close(); } }
Download JSON Jar file.
Output:
Technorati Tags: AJAX & JSON
Comments
Post a Comment