1

i read myself a bit into JSONP... but it feels like I am still dumb. I created the following page, which should get the information by my webservice in a JSON notation:

<html>
<head>
<title> SomeHtml Form </title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript"></script>

<script type="text/javascript">
function getParameters(){
    $.getJSON('http://localhost:8080/test/services/export/getuser.mvc?callback=?',function(res){
        alert('Your name is '+res.lname);
    });
}
</script>
</head>

<body >
    <button onclick="getParameters();">Get Name</button>
</body>
</html>

I created this with the help of Liams Comment on this topic: Simple jQuery, PHP and JSONP example?

UPDATE 13-07-2012 15:06 I managed to get the right result from my Servlet, but now I get a different error from the receiving website ("Error: res is not defined"). What would be the right key, for my JSONP data, so the site can read it?

On the other hand I have a webservice using SPRING and Java Servlets, which gets called by $.getJSON('http://localhost:8080/test/services/export/getuser.mvc?callback=?',...) This service looks like this:

@Controller
@RequestMapping("/services/export/")
public class AccountServiceProviderController extends ProfileDashboardController {

    private static final String DESC_NAME = "ACCOUNT SERVICE PROVIDER CONTROLLER";


    @RequestMapping("/getuser")
    public @ResponseBody
    JSONPObject list(final HttpServletResponse response) {

        return new JSONPObject("res", getJson());

    }

    public JSONObject getJson() {
        User user = getCurrentUser();

        // logger.debug("ID: " + id);

        // json
        JSONObject json = new JSONObject();
        json.put("lname", user.getLastName());
        json.put("fname", user.getFirstName());

        logger.info(json.toString());
        return json;

    }

}

Unfortunately I never get an alert. What did I do wrong?

UPDATE What does this error message: "res not found" mean. What does it has to name like to be found?

Community
  • 1
  • 1
DonMarco
  • 405
  • 2
  • 14
  • 34
  • If you call the GET service in your browser directly (http://localhost:8080/test/services/export/getuser.mvc?callback=?). Is the output correct? – theforce Jul 13 '12 at 11:59
  • Jap. I debuged the Java Part and that is putting everything perfectly together. The Output is this: http://localhost/someProject/someHtml.php?callback={"lname":"Andreae","fname":"Volker"} But maybe in the Java-Part the "sendRedirect(url)" is wrong and it should not be a redirect? But how else would I get the data back to the initial page? – DonMarco Jul 13 '12 at 12:00
  • o.k, this is good news - the backend (your controller) works fine. – theforce Jul 13 '12 at 12:06
  • Well, I am not quiet sure: I found an excerpt how to replace $.getJSON with a function, that talks a bit more, so I tried this: `$.ajax({ url: 'http://localhost:8080/test/services/export/getuser.mvc?callback=?', dataType: 'json', success: function(result){ alert("token recieved: " + result.token); }, error: function(request, textStatus, errorThrown) { alert("ERROR"); }, complete: function(request, textStatus) { //for additional info alert("COMPLETE"); } });` and I get as answer ERROR and COMPLETE, with textstatus = parseerror and request.responseText = undefined What does that mean? – DonMarco Jul 13 '12 at 12:27
  • parseerror means that the browser couldn't parse the response as json. I'd go back & make sure you are passing back proper json. Paste your output into http://jsonlint.org. – olore Jul 14 '12 at 03:06
  • The Result was proper JSON, since a JSON class (in Java) build that JSON. The error was, that the result is JSON, but has to be interpreted as Javascript (otherwise the function $.getJSON doesn't work) and therefor the resulttype has to be changed! – DonMarco Jul 16 '12 at 07:06

1 Answers1

3

Okay... I found the error. The above stated code works, if you have stated the following:

  response.setContentType("text/javascript; charset=UTF-8");

The complete working Code would look like this (Servlet):

@Controller
@RequestMapping("/secure/profile/services/export/")
public class AccountServiceProviderController extends ProfileDashboardController {

    private static final String DESC_NAME = "ACCOUNT SERVICE PROVIDER CONTROLLER";


    @RequestMapping("/getuser")
    public @ResponseBody
    JSONPObject list(@RequestParam("callback") final String callback, final HttpServletResponse response) {

        response.setContentType("text/javascript; charset=UTF-8");

        return new JSONPObject(callback, getJson());

    }

    public JSONObject getJson() {
        User user = getCurrentUser();
        JSONObject json = new JSONObject();

        // User muss eingeloggt sein
        if (user != null) {
            json.put("lname", user.getLastName());
            json.put("fname", user.getFirstName());

            logger.info("Daten werden exportiert: " + json.toString());
            return json;
        }
        return null;

    }

}
DonMarco
  • 405
  • 2
  • 14
  • 34