Json response can't not be evaluated by eval - ajax

**index.jsp (client side)**
**************************************************************************************
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Techniques AJAX - XMLHttpRequest</title>
<script type="text/javascript" src="oXHR.js"></script>
<script type="text/javascript">
<!--
function request(callback) {
var xhr = getXMLHttpRequest();
xhr.onreadystatechange = function(){
if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) {
alert(xhr.responseText);
var text = xhr.responseText;
var myObject = eval('(' + text + ')');
callback(myObject.Addresses);
}
};
xhr.open("GET", "jsonResponse.jsp", true);
xhr.send(null);
}
function readData(oData) {
alert(oData);
}
function getXMLHttpRequest() {
var xhr = null;
if (window.XMLHttpRequest || window.ActiveXObject) {
if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
} else {
xhr = new XMLHttpRequest();
}
} else {
alert("Votre navigateur ne supporte pas l'objet XMLHTTPRequest...");
return null;
}
return xhr;
}
//-->
</script>
</head>
<body>
<p>
<button onclick="request(readData);">Afficher le fichier XML</button>
<div id="output"></div>
</p>
</body>
</html>
***jsonResponse.jsp (server side)***
**********************************************************************************
<%--
Document : jsonResponse
Created on : Mar 4, 2012, 8:39:23 PM
Author : ghorbel
--%>
<%#page import="org.json.JSONException"%>
<%#page import="org.json.JSONArray"%>
<%#page contentType="text/html; charset=UTF-8"%>
<%#page import="org.json.simple.JSONObject"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Hello World!</h1>
<%
JSONObject json = new JSONObject();
JSONArray addresses = new JSONArray();
JSONObject address;
try
{
int count = 15;
for (int i=0 ; i<1 ; i++)
{
address = new JSONObject();
address.put("CustomerName" , "Decepticons" + i);
addresses.put(i,address);
}
json.put("Addresses", addresses);
}
catch (JSONException jse)
{
}
response.getWriter().flush();
response.setContentType("application/json");
response.getWriter().write(json.toString());
%>
</body>
</html>
The result of 'alert(xhr.responseText);' (the json return response from the server).
*************************************************************************************************
{"Addresses":[{"CustomerName":"Decepticons0"}]}
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Hello World!</h1>
</body>
</html>
****************************************************************************************
The problem here that the 'var myObject = eval('(' + text + ')');' cannot evaluate the json return response from the server.(the result is just above).
My question. Why the result contains these extra linges.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
</body>
</html>
when it' supposed to return just
{"Addresses":[{"CustomerName":"Decepticons0"}]}.
If someone can tell me what's wrong with the program.
I use Netbeans , Glassfish.
Thanks in advance.

As well as your code your JSP contains literal HTML. You only want the <%#page import...%> and your central code inside <% ... %> that does the work.

Related

String is null on Thymeleaf page after adding to model

My controller:
#Controller
public class IndexController {
#RequestMapping(value = "/index")
public String index(Model model) {
model.addAttribute("message", "Hello World!");
return "index";
}
}
My page:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset = "ISO-8859-1" />
<link href = "css/styles.css" rel = "stylesheet"/>
<title>Spring Boot Application</title>
</head>
<body>
<h4>Spring boot.</h4>
<p th:utext="${message}"></p>
</body>
</html>
Upon loading and rendering, this HTML appears; how do I get the message to appear?
<!DOCTYPE html>
<html>
<head>
<meta charset = "ISO-8859-1" />
<link href = "css/styles.css" rel = "stylesheet"/>
<title>Spring Boot Application</title>
</head>
<body>
<h4>Spring boot.</h4>
<p></p>
</body>
</html>
Ensure you have imported the thymeleaf dependency into your project.
Use th:text="${message}"
Method in IndexController is never being called, because this:
#RequestMapping(value = "/index")
Should be this:
#RequestMapping(value = "/")

Spring: ModelMap attributes are not shown in jsp

my data, which I try to pass from my controller to the view is apparently ignored. The console doesn't output any errors. Can somebody point me to the apparently obvious mistake I did?
Controller
#RequestMapping("/notes")
public String index(ModelMap model) {
String test = "Hello Felix";
model.addAttribute("hello", test);
return "notes";
}
View
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# page contentType="text/html; charset=UTF-8" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Notes</title>
</head>
<body>
<h1>${hello}</h1>
</body>
</html>
HTML Source
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Notes</title>
</head>
<body>
<h1></h1>
</body>
</html>
You need to return the model, something like the following should work:
Map model = ...
model.put(name, value);
return new ModelAndView(view, model);

Using JSONText in Django

I'm using JSONText to load a JSON call in my Jquery but for some reason the request is failing,
Here is the code,
urls.py
urlpatterns = patterns('',
#JSON Response
(r'^json/$', json_request)
)
views.py
from django.utils import simplejson
def json_view(request):
print 'json_view being called'
to_json = {
"key1": "value1",
"key2": "value2",
"key3": "value3",
"key4": "value4"
}
return HttpResponse(simplejson.dumps(to_json), mimetype='application/json')
def json_request(request):
variables = RequestContext(request)
return render_to_response('ajaxtest.html',variables)
ajaxtext.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=ISO-8859-1">
<title>Insert title here</title>
<style>
#mainViewContainer{
background-color:red;
height:100px;
width:200px
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
var main_container = $("<div>").attr("id", "mainViewContainer");
main_container.append($('<div id="table_layout" />')
.append($('<table id="table_set"/>').
append('<thead><tr> <th>ID</th><th>Name</th> <th>DOB</th> <th>Date Enrolled</th> </tr></thead>')));
$.getJSON("/json_view",function(census_data){
$(census_data).each(function(k,v){
$('#table_set').append();
trObj = $('<tr>');
trObj.append($('<td>').html(v.key1));
trObj.append($('<td>').html(v.key2));
trObj.append($('<td>').html(v.key3));
trObj.append($('<td>').html(v.key4));
$('#table_set').append(trObj);
});
main_container.appendTo(document.body)
});
</script>
</head>
<body>
</body>
</html>
You don't have a route for json_view in your urls.py. Try to add one:
urlpatterns = patterns('',
#JSON Response
(r'^json/$', json_request)
(r'^json_view/$', json_view)
)
(note the slash at the end of ^json_view/)

passing string to jsp, whats wrong?

In a Controller, I have a handler method that should pass a string to a jsp named searchResultGraph.jsp
#RequestMapping(value = PATHELEM + "/searchGraph")
public String handleGraph(Model model) {
String write = writer.getWriteString();
model.addAttribute("write", write);
System.out.println(write);
return PATHELEM + "/searchResultGraph";
}
the jsp looks like this:
<?xml version="1.0" encoding="ISO-8859-1" ?>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="core"%>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Graph View</title>
<script type="text/javascript" src="<c:url value="/resources/js/json2.min.js" />"></script> <!-- ${pageContext.request.contextPath}/WebContent/WEB-INF/views/ -->
<script type="text/javascript" src="<c:url value="/resources/js/cytoscapeweb.min.js" />"></script>
<script type="text/javascript" src="<c:url value="/resources/js/AC_OETags.min.js" />"></script>
<script language="JavaScript">
window.onload=function() {
// network data could alternatively be grabbed via ajax
var xml = '${write}';
// init and draw
// initialization options
var options = {
swfPath: "CytoscapeWeb",
flashInstallerPath: "playerProductInstall"
};
var vis = new org.cytoscapeweb.Visualization("cytoscapeweb", options);
var draw_options = {
// your data goes here
network: xml,
// show edge labels too
edgeLabelsVisible: false,
edgeTooltipsEnabled:true,
// let's try another layout
layout: "circle",
// hide pan zoom
panZoomControlVisible: true
};
vis.draw(draw_options);
};
</script>
<style>
/* The Cytoscape Web container must have its dimensions set. */
html, body { height: 100%; width: 100%; padding: 0; margin: 0; }
#cytoscapeweb { width: 100%; height: 100%; }
</style>
</head>
<body>
<h1>The Graph</h1>
<h1>${write}</h1>
<div id="cytoscapeweb">
Cytoscape Web will replace the contents of this div with your graph.
${write}
</div>
</body>
</html>
But nothing is displayed when I try to call ${write}. Is there something missing in my method?
Thanks!
CHECK ARE YOU HAVING A METHOD NAMED getWriteString(); in you bean class and if not create a class name Write and instantiate an object named write in your controller and then pass some string into that and add that to the model to return that by you controller,
Write write = new Write();
write.getWriteString();
Ok, I found the solution:
The links in options-tag had to be relative links too!
So instead of this
var options = {
swfPath: "CytoscapeWeb",
flashInstallerPath: "playerProductInstall"
};
I had to write this:
var options = {
swfPath: "<c:url value="/resources/js/CytoscapeWeb" />",
flashInstallerPath: "<c:url value="resources/js/playerProductInstall" />"
};

Not able to make Ajax call using jquery

I am trying to call a Sample API from my JSP using jQuery Ajax, but I am not getting success. I dont know where am I wrong but even simple html page is not getting loaded.
Here is my code.
<%# 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>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
Hello
<div id="temp">
<a href="#" onclick="callGetApplicationDetails();" >Click Here</a>
</div>
<script type="text/javascript">
function callGetApplicationDetails()
{
$.ajax({
url:"serverFile.jsp",
type: "GET",
dataType:'html',
async: true,
data:data,
success: function(responseData) {
if (responseData != null && callback != null) {
alert('success');
$('#temp').html(responseData);
}
},
error: function(){
alert('error');
if (errorCallback !=null) errorCallback();
}
});
}
</script>
</body>
</html>
Even the alert is not popping up of success and failure.
Pls help.
thanks
Hemish
I suggest that you use firebug, and check that the request is making it to the server.

Resources