Jump to content

Problem With Xmlhttp Request In Combi With Jsp


kmalk
 Share

Recommended Posts

Hi!1st: I'm a beginner with ajax, jsp, js .. but ..2nd: I have a (OpenLayers) Map with markers on it, which have an ID/title and are representing some coordinates.I write a search class with JAVA, that delivers the searched title and coordinates and places the results on top of the map in a table through JSP.This results are links with a JS onclick event. When a title is clicked, the JS function has to find the proper coordinates and zoom in to the map. Everything seemed to work, but when I wanted to show the results, the shown results were only visible for the time the page was updating.Then the results disapered. Now I want to use the XMLHTTPRequest to stop the reloading of my site. But .. it doesn't work... And I don't now why. (Have I maybe forgotten something?! Does it work this way anyway?!)3rd: Any help or idea to the way of a result are SO welcome!4th: THE code ^^ A part of my jsp code: index.jsp

 <tom:div styleClass="searchWrapper">  <tom:div styleClass="searchContent">    <!-- search value input -->    <h:form acceptcharset="utf-8" id="searchForm">                  <h:inputText id="search" alt="inputfield" binding="#{Traders.searchField}"      value="#{Traders.searchValue}" maxlength="20" size="20" styleClass="input"></h:inputText>      <h:commandButton alt="search" action="#{Traders.search}" value="#{fields.search}"       styleClass="button" onmouseup="window.setTimeout(myAjaxInit(), 3000);"></h:commandButton>      <h:commandLink value="#{fields.searchOpt}" styleClass="linkStyle"></h:commandLink>     </h:form><!-- searchForm end -->  </tom:div><!-- searchContent end --></tom:div><!-- searchWrapper end --><h:form id="searchResults" > <div id="sideMenu" > <div>  <%-- room for searchResults --%> </div> </div><!-- sideMenu end --></h:form><!-- searchResult end -->

A part of my js code: init.js

//fetch this filevar parameter = "txtData/searchResults.xml";var request = null;var url = "http://localhost:8084/ms2-web-monitoring-mockup/monitor/index.jsp"; /** * communication between client- js and server- jsp * show searchResults without reloading the page */function myAjaxInit() {    if( window.XMLHttpRequest ) {      //for IE7, FF, Mozilla, .. (new browser)      request = new XMLHttpRequest();    } else if( window.ActiveXObject ) {      //for IE5, IE6    .. (old browser)      request = new ActiveXObject( "Microsoft.XMLHTTP" );    } else {      alert('Dieser Browser unterstützt leider kein AJAX.');      return;    }//end if else window.XMLHttpRequest    if (request != null) {      //when state is changing, run this function      request.onreadystatechange = changeState;      //GET request, fetch homepage, use asynchronous request      request.open( "POST", url, true );      request.setRequestHeader("Content-Type", "text/plain;charset=UTF-8");      //send request with xml file      request.send( parameter );          } else {      alert('Dieser Browser unterstützt leider kein XMLHTTP.');    }//end if esle request != null}//end function meinAjaxInitfunction changeState(){  if( request.readyState == 4 ) {     //200 = ok, 304 = not modified    if ( request.status == 200 || request.status == 304 ) {      //write responseText in div with id=sideMenu      //alert(request.responseText);      //document.getElementById('sideMenu').innerHTML = request.responseText;      //exectue function, in which responseXML is written as      //table into a div with id=sideMenu      showXMLfile(request.responseXML);    } else {      alert('HTTP Status-Code: ' + request.status + ' - ' +            'Es ist ein Problem beim Erhalten der XML Daten' +            'aufgetreten.');    }//end if else request.status == 200  } else {    //test    alert('something happen');  }//end if else request.readyState == 4}//end function changeState

.. thx a lot.

Edited by kmalk
Link to comment
Share on other sites

Hi! :)Here it is: JSP generated HTML

<!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=UTF-8">      <meta http-equiv="Content-Script-Type" content="text/javascript" >      <meta http-equiv="Content-Style-Type" content="text/css">      <title>MyTitle</title>            <script type="text/javascript" src="http://www.openlayers.org/api/OpenLayers.js"></script>      <script type="text/javascript" src="javaScripts/initLayer.js"></script>            <link type="text/css" rel="stylesheet" href="css/ms2_GraBO.css" media="screen">  </head>  <body onload="init()">    <div id="main_content"><!-- contains search and THE map -->          <div class="searchWrapper">        <div class="searchContent">          <form id="searchForm" name="searchForm" method="post" 		accept-charset="utf-8"                 action="/ms2-web-monitoring-mockup/monitor/index.jsp;jsessionid=AB1698BF028DE89869A443F79221DA0B" 		enctype="application/x-www-form-urlencoded">      <!-- search -->          <input id="searchForm:search" name="searchForm:search" type="text" value="" 			alt="inputfield" maxlength="20" size="20" class="input" />      <script type="text/javascript"><!--	function oamSetHiddenInput(formname, name, value)	{		var form = document.forms[formname];		if(typeof form.elements[name]=='undefined')		{			var newInput = document.createElement('input');			newInput.setAttribute('type','hidden');			newInput.setAttribute('id',name);			newInput.setAttribute('name',name);			newInput.setAttribute('value',value);			form.appendChild(newInput);		}		else		{			form.elements[name].value=value;		}	}		function oamClearHiddenInput(formname, name, value)	{		var form = document.forms[formname];		if(typeof form.elements[name]!='undefined')		{			form.elements[name].value=null;		}	}		function oamSubmitForm(formName, linkId, target, params)	{		var clearFn = 'clearFormHiddenParams_'+formName.replace(/-/g, '\$:').replace(/:/g,'_');		if(typeof eval('window.'+clearFn)!='undefined')		{			eval('window.'+clearFn+'(formName)');		}				var oldTarget = '';		if((typeof target!='undefined') && target != null)		{			oldTarget=document.forms[formName].target;			document.forms[formName].target=target;		}		if((typeof params!='undefined') && params != null)		{			for(var i=0; i<params.length; i++)			{				oamSetHiddenInput(formName,params[i][0], params[i][1]);			}		}				oamSetHiddenInput(formName,formName +':'+'_idcl',linkId);				if(document.forms[formName].onsubmit)		{			var result=document.forms[formName].onsubmit();			if((typeof result=='undefined')||result)			{				document.forms[formName].submit();			}		}		else 		{			document.forms[formName].submit();		}		if(oldTarget==null) oldTarget='';		document.forms[formName].target=oldTarget;		if((typeof params!='undefined') && params != null)		{			for(var i=0; i<params.length; i++)			{				oamClearHiddenInput(formName,params[i][0], params[i][1]);			}		}				oamClearHiddenInput(formName,formName +':'+'_idcl',linkId);return false;	}//--></script>	  <input id="searchForm:_idJsp5" name="searchForm:_idJsp5" type="submit" 		value="suchen" onclick="if(typeof window.clearFormHiddenParams_searchForm!='undefined')		{clearFormHiddenParams_searchForm('searchForm');}" alt="search" 		onmouseup="window.setTimeout(myAjaxInit(), 2000); [b]return false;[/b]" class="button" /> // I noticed that I forgot [b]this[/b] to prevent the page from reload          <a href="#" onclick="return oamSubmitForm('searchForm','searchForm:_idJsp6');" 			id="searchForm:_idJsp6" class="linkStyle">Suchoptionen</a> //searchoptions	  <input type="hidden" name="searchForm_SUBMIT" value="1" />	  <input type="hidden" name="searchForm:_link_hidden_" />	  <input type="hidden" name="searchForm:_idcl" /><script type="text/javascript"><!--	function clear_searchForm()	{		clearFormHiddenParams_searchForm('searchForm');	}		function clearFormHiddenParams_searchForm(currFormName)	{		var f = document.forms['searchForm'];		f.elements['searchForm:_link_hidden_'].value='';		f.elements['searchForm:_idcl'].value='';		f.target='';	}		clearFormHiddenParams_searchForm();//--></script>		[b]//this was reduced to 1/5th ! (can you maybe tell me for what this value is?)[/b]	  <input type="hidden" name="javax.faces.ViewState" id="javax.faces.ViewState" value="rO0ABXVyABNbTGphdmEubGFuZy5PYmplY3Q7kM5YnxBzKWwCAAB4+AARbAAdfZmFjZXRzdAATW0xqYXZhL2xhbmcvT2JqZWN0O3hwdXIASltb3JnL+AAcAAAADc3EAfgACcHQANG9yZy5hcGFjaGUubXlmYWNlcy5jbBQQ==" />	</form><!-- searchForm end -->      </div><!-- searchContent end -->    </div><!-- searchWrapper end -->           <form id="searchResults" name="searchResults" method="post"                 action="/ms2-web-monitoring-mockup/monitor/index.jsp"                 enctype="application/x-www-form-urlencoded">      <div id="sideMenu">        <div>        </div>      </div> <!-- sideMenu end -->      <input type="hidden" name="searchResults_SUBMIT" value="1" />      <input type="hidden" name="javax.faces.ViewState" id="javax.faces.ViewState"       value="rO0ABXVyABNbTGphdmEubGFuZy5PYmplY3Q7kM5YnxBzKWwCAAB4cAAAAANzcg      +QAAAAAAADHcIAAAAEAAAAAB4cHBwcHBwcHBwcHBwcHBwcHBwcHBwcHBwcHVxAH4AA      +AAAAAAAFdXEAfgAAAFBxAH4AUnhwcHBwcHBwcHBweHhxAH4AQw==" /> [b]//this was also reduced[/b]    </form><!-- searchResult end -->  </div><!-- end main_content --></div> <!--end wrapper--><!-- MYFACES JAVASCRIPT --></body></html>

I deleted the irrelevant parts.The showXMLfile() is a "simple" function, in which I go through the XML file, pick my needed infos and put them line by line in a table.Here the code:

function showXMLfile(object){var rows = object.getElementsByTagName('Trader');  var listText = "<tom:panelGrid  columns='1' columnClasses=',dataScroller' >" +        "<!-- sideMenu --> " + "\n" +        "<tom:dataTable id='data' var='trader' rows='14' " +               "value='#{Traders.traderListResult}' " +        "preserveDataModel='false' renderedIfEmpty='yes' " +        "styleClass='searchResultsContent'> " + "\n";  for (i=0, row; row=rows[i]; i++) {    var elements = row.childNodes;    for (var j=0, srow; srow=elements[i]; j++) {      if (srow.nodeType == 1 ) {        //start first column        listText += "<tom:column>" + "\n";        //set ICON        if(object.getElementsByTagName('icon')){          listText += "<tom:graphicImage styleClass='iconsStyle' url='#{" +            srow.firstChild.data + "}' alt='Icon' />";        } else {          listText += "<tom:graphicImage styleClass='iconsStyle' " +            "alt='Icon' />";        }//end if else ICON        //end first and start second column        listText += "</tom:column>" + "\n" + "<tom:column>";        //set TITLE        if(object.getElementsByTagName('title')){          listText += "<tom:commandLink value='#{"            + srow.firstChild.data + "}' ";        } else {          listText += "<tom:commandLink value='TITEL' ";        }//end if else TITLE        //set POINT        if(object.getElementsByTagName('point')){          listText += "onmouseup='setCenter(#{"            + srow.firstChild.data + "})'/>";        } else {          listText += "onmouseup='alert(\" Unfortunately the destination " +            "is unknown!\")'/>";        }//end if else POINT        //end second column        listText += "</tom:column>" + "\n";              }//end if srow.nodeType == 1    }//end for j    listText += "\n";  }//end for i    //add tom:dataScroller to listText  addPageNavigation(listText);  //end table and panelgrid  listText += "</tom:dataTable>" + "\n";  listText += "</tom:panelGrid>" + "\n";  //show table  document.getElementById('sideMenu').innerHTML = listText;}//end function showXMLfile

By the way:It is so, that "value='#{Traders.traderListResult}' " (this are the results found by JAVA) creates the lines, right?!That would duplicate my output, or?!

Edited by kmalk
Link to comment
Share on other sites

You can't have the showXMLfile function output JSP code, the browser doesn't understand JSP code. The browser understands HTML, so your function needs to output regular HTML. The JSP code is evaluated on the server but Javascript doesn't run on the server, it runs in the browser. So it's not going to automatically transform the JSP code into HTML, it's just going to give the browser a bunch of JSP code that the browser isn't going to know what to do with.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...