1

I've made a RESTful web service at localhost in Java. When I type the following url in my navigator address bar :

http://localhost:8080/GeonotesApp2-war/webresources/route/1

It will give me :

{"rid":"1","routeComment":"hhhahahahah","routeDateCreate":"2012-04-03T00:00:00+02:00","routeDistance":"13400.0","routeName":"route1","routeUserId":"1"}

Now I want to use an Ajax call to get this JSON information with this script :

<html >
<head>
    <meta charset="utf-8">
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script>
    $(function(){
        $.ajax({
            type: "GET",
            url: "http://localhost:8080/GeonotesApp2-war/webresources/route/1",
            dataType: 'json',
            headers: {
                Accept: "application/json",
                "Access-Control-Allow-Origin": "*"
            },
            success: function(resp) {
                alert("success");
            },
            error: function(e) {
                alert("error: "+e);
            }
        });
    });

</script>   
</head>
<body>
    Hello Test Service!
</body>

However I'm always getting the error message :

error: [object Object]

I found this post and followed exactly what it does, but doesn't work. Can anyone tell me why? Thanks

Calling Rest webservice using JQuery Ajax call , web service is returning JSON string

3
  • 3
    Change your error handler to function (jqXHR, textStatus, errorThrown ), then you can see what the actual error is. The [object Ojbect] you're getting back is the jqXHR object. Commented Apr 22, 2013 at 16:56
  • 1
    @G_M I've tried change error handler to function(jqXHR, textStatus, errorThrown), I alert textStatus, it displays : error : error, when I alert errorThrown, there is nothing after 'error:' Commented Apr 22, 2013 at 17:03
  • What about jqXHR.responseText? Commented Apr 22, 2013 at 17:06

1 Answer 1

4

The headers have to be on the service side. So the browser knows that the server allows this website to use Ajax to load the data. So these headers:

Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: GET

Links:

Sign up to request clarification or add additional context in comments.

1 Comment

Only if you load from a different domain. Otherwise you will get a security error

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.