2

enter image description here My Controller:

@RequestMapping(value = "jobs")
public void removeJobs(@RequestParam("username") String username, Model model) {
   String []jobs = jobsFetcher(username);
   model.addAttribute("list", jobs); 
}

My Jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!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">
   <title>Insert title here</title>
   <link type="text/css" rel="stylesheet"
href="<c:url value="public/files/styles/jobManager.css" />" />

<script type="text/javascript">
function ajaxFunction(username) {
    var xmlhttpReq = crossBrowserAjaxObject();
    if (xmlhttpReq) {
        xmlhttpReq.open("get", "jobs", true);
        xmlhttpReq.onreadystatechange = handleServerResponse(xmlhttpReq);
        xmlhttpReq.setRequestHeader('Content-Type',
                'application/x-www-form-urlencoded');
        xmlhttpReq.send("username=" + username);
    }
}

function crossBrowserAjaxObject() {
    var xmlhttp;
    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    } else {// code for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    return xmlhttp;
}

function handleServerResponse(xmlhttpReq) {
    //var xmlhttp = new XMLHttpRequest();
    return function() {
        alert(xmlhttpReq.readyState);
        if (xmlhttpReq.readyState == 4 && xmlhttpReq.status == 200) {
            alert(xmlhttpReq.responseText); // this is ok
            // HERE HOW DO I GET THE MODEL OBJECT AS A RESPONSE COMMING FROM SERVLET &
            // USE IN MY JSP FILE ?
        }
    };
}
</script>
</head>
<body>
<div>
    <div class="leftDiv">
        <a href="#" onclick="ajaxFunction('JAMES')">JAMES</a> 
        <a href="#" onclick="ajaxFunction('David')">David</a> 
        <a href="#" onclick="ajaxFunction('Catrina')">Catrina</a> 
        <a href="#" onclick="ajaxFunction('Cathy')">Cathy</a> 
        <a href="#" onclick="ajaxFunction('Paul')">Paul</a>
    </div>

    <div class="rightDiv">
        <!-- HOW DO I GET THE JOB LIST & USE IT HERE USING MY AJAX ? -->
        <c:forEach items="???" var="task">
            <p>${task}</p>
        </c:forEach>
    </div>
</div>
</body>
</html>

Now As I have mentioned inside the picture, I want my right div element change when I click the employees without refreshing the whole page.

the only thing which I don't know is when the xmlhttpReq.responseText returns to me, how I'm gonna fetch the modelelement which does carry an Array of jobs using Ajax & use it to render the page...

in another words how I will be able to fetch the parameters coming from my controller after Ajax call & use Ajax itself to make my page ?

Do you any Idea or suggestion or something that can help me go through this ?

( By The way These codes are not yet tested! )

3 Answers 3

4

Spring MVC 3 and JQuery is one of the great combination to perform the ajax request and response. You need this jar "jackson-mapper-asl".Define the removeJobs controller which handles the Ajax request and return the json response. @ResponseBody converts the custom object into equivalent json response object.

function madeAjaxCall(){ $.ajax({ type: "post", url: "jobs", cache: false,  data:{key:value;key:value}, success: function(response){ //user your data for view }, error: function(){    alert('Error while request..'); } }); } - 
Sign up to request clarification or add additional context in comments.

Comments

3

take a look at jquery it makes ajax requests rather simpler.

You need to change the controller method to include the annotation @responsebody on return type. Don't add stuff to the model for ajax requests, it won't work unless you return a new ModelAndView .

here is an intro

4 Comments

I saw that, looks good & helpful but It didn't cover my main question. I want to knoe how to use model attribute coming from the controller after an ajax request & use it inside the jsp page ?
you can't use the model with ajax requests, unless you return a new model and view (which opens a new page). Which kinda defeats the point of ajax in the first place.
Can you explain more or show me any specification that cover everything in relation between AJAX & Servlet ?
You can absolutely return a model with an ajax request. It depends on how you structure your views. For example, you can return a view that represents an html "chunk" and that is bound to a model object.
1

Once you use the @Responsebody annotation NimChimpsky mentioned, the value of xmlhttpReq.responseText would be a JSON encoded string. Take a look at this post which explains how to parse a JSON string: Parse JSON in JavaScript?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.