Thursday, 11 April 2013

Java - How to use Ajax in JSP

Home » Tutorials » Java - How to use Ajax in JSP

Java - How to use Ajax in JSP

Ajax is become so popular in web, everyone want to use Ajax in JSP application. Ajax got big popularity after Google used in their application gmail. Java also watching Ajax power and realized that Ajax is important part of any web application. It should be implemented in JSP, struts projects.
Ajax allows us to load page in background without refreshing and submitting full page. Ajax is simple JavaScript script which work with XML Http request.

How to use Ajax in JSP
1. Ajax framework for java
2. Simple Ajax script for JSP

Ajax framework for java
Frameworks for Ajax in java are available from many third party websites. This Ajax framework can easily implement in any java application e.g. struts, JSP, Servlet. This Ajax framework comes in taglib and tags can use in front end page JSP.
You can check and download these ajax framework
http://ajaxtags.sourceforge.net/
http://ajaxanywhere.sourceforge.net/
https://ajax.dev.java.net/

Simple Ajax script for JSP
Lot of script is available for auto complete, load page, validation, and menu navigation in Ajax which can use in JSP.
A simple example of ajax show you to use in JSP
index.jsp
<html>
<head>
<script src="ajaxjs.js"></script>
</head>
<body>
<a href="javascript:loadContent('parameterValue')">Load Ajax content</a>
<div id="prtCnt"></div>
</body>
</html>
ajaxjs.js
var xmlhttp
function loadContent(str)
{
 xmlhttp=GetXmlHttpObject();
  if (xmlhttp==null)
  {
   alert ("Your browser does not support Ajax HTTP");
   return;
  }
    var url="loadJSP.jsp";
    url=url+"?q="+str;
    xmlhttp.onreadystatechange=getOutput;
    xmlhttp.open("GET",url,true);
    xmlhttp.send(null);
}
function getOutput()
{
  if (xmlhttp.readyState==4)
  {
  document.getElementById("prtCnt").innerHTML=xmlhttp.responseText;
  }
}
function GetXmlHttpObject()
{
    if (window.XMLHttpRequest)
    {
       return new XMLHttpRequest();
    }
    if (window.ActiveXObject)
    {
      return new ActiveXObject("Microsoft.XMLHTTP");
    }
 return null;
}
JSP file which load in background
loadJSP.jsp
<%@ page contentType="text/html; charset=iso-8859-1" language="java" %>
<%
 String q =request.getParameter("q");
 String str="This is JSP string loading from JSP page in ajax, loading time :";
 java.util.Date dt=new java.util.Date();
 out.print(str+dt);
%>
source: easywayserver

0 comments:

Post a Comment