// File jsonpscript.js // The cooljsonp function takes a URL and a callback function name. // It creates a script tag in the html head section. // When this script is fetched the servlet runs and returns json // padded with the name of the function. That is, the server returns // myCallback({some JSON object}) // The client will call myCallback({some JSON object}) // The script tag is removed from the DOM on completion. function cooljsonp(url,myCallback) { alert("Calling " + url + " with " + myCallback + " for callback"); var head = document.head; var script = document.createElement("script"); script.setAttribute("src", url + '?' + 'method=' + myCallback); head.appendChild(script); head.removeChild(script); } function callBackHandler(jsonObject) { alert("callBack called"); // display the id property value // treating it as a JSON object alert(jsonObject.id); // covert the jsonObject to a String var response = JSON.stringify(jsonObject); alert(response); } // JSONServlet.java @WebServlet(urlPatterns = {"/JSONServlet"}) public class JSONServlet extends HttpServlet { protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); // display on server console System.out.println("JSON Servlet has a visitor"); try (PrintWriter out = response.getWriter()) { // the query parameter is method=callbackName String name = request.getParameter("method"); // name is the callBack // return JSON object as a String {"id" : "mike"} out.println(name + "({\"id\" : \"mike\" })"); } }