2

I have made a Rest Web Service:

package org.jboss.samples.rs.webservices;


import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.GET;
import javax.ws.rs.Path;



@Path("/MyRESTApplication")
public class HelloWorldResource {


    @GET()
    @Produces("application/json")
    @Path("/dealInfo/{dealId}")
    public String sayHello(@PathParam("dealId") int dealId) {
        System.out.println("dealid......"+dealId);
        switch(dealId) {
        case 1 :System.out.println("employee id.....");
            return "{'name':'George Koch', 'age':58}";
        case 2:
            return "{'name':'Peter Norton', 'age':50}";
        default:
            return "{'name':'unknown', 'age':-1}";
    } // end of switch

    }
}

When I go to internet explorer & type this in the address bar:

http://localhost:8080/nagarro-0.0.1-SNAPSHOT/MyRESTApplication/dealInfo/2

It is giving me:

{'name':'Peter Norton', 'age':50}

But when I call it using an ajax call in a JQuery method. e.g.

$.ajax({  
           type: "GET",  
           url: "http://localhost:8080/nagarro-0.0.1-SNAPSHOT/MyRESTApplication/dealInfo/2",  
           data: "",  
           success: function(resp){  
             // we have the response  
             alert("Server said123:\n '" + resp + "'");  
           },  
           error: function(e){  
             alert('Error121212: ' + e);  
           }  
         });

I am getting an Error in this call.

enter image description here

When I am debugging using F12 in IE, I am getting following as well

"Invalid JSON: {\'name\':\'Peter Norton\', \'age\':50}"

Would anybody tell me what could be the problem in my call.

Sunny Gupta
  • 6,929
  • 15
  • 52
  • 80

3 Answers3

4

Your service and output is right.

Problem is same orgin policy http://en.wikipedia.org/wiki/Same_origin_policy

Ajax does not allow access to inner level service. For example, in the www.example.com/index.html, you can not access www.example.com/service/book?id=1. Because you changed your context path from www.example.com to www.example.com/service/book. This is not allowed for security but we have one solution

Previously, I had same problem and I solved it with below code. I think it can help you. Key point is dataType: 'json'


    function testService()
                {
                    $.ajax(
                    {
                        dataType: 'json',
                        headers: {
                            Accept:"application/json",
                            "Access-Control-Allow-Origin": "*"
                        },
                        type:'GET',
                        url:'http://localhost:8080/service/book/search/1',
                        success: function(data)
                        {
                            document.writeln("Book id : " + data.id);
                            document.writeln("Book title : " + data.name);
                            document.writeln("Description : " + data.description);
                        },
                        error: function(data)
                        {
                            alert("error");
                        }
                    });
                }

karthikr
  • 97,368
  • 26
  • 197
  • 188
Validus Oculus
  • 2,756
  • 1
  • 25
  • 34
3

I think that you are not returning a valid json: try something like:

  return  "{\"name\":\"unknown\", \"age\":-1}"

because this

{
    "name": "unknown",
    "age": -1
}

is a valid JSON (You must use ", not ') while this is not

{
    'name': 'unknown',
    'age': -1
}

You should also specify the datatype

 $.ajax({  
       type: "GET",  
       url: "http://localhost:8080/nagarro-0.0.1-SNAPSHOT/MyRESTApplication/dealInfo/2",  
       dataType: "json",  
       success: function(resp){  
         // we have the response  
         alert("Server said123:\n '" + resp.name + "'");  
       },  
       error: function(e){  
         alert('Error121212: ' + e);  
       }  
     });
Nicola Peluchetti
  • 76,206
  • 31
  • 145
  • 192
  • 1
    it is working fine, but I just want to know that whenever we specify @Produces(application/json) then why there is a need to give datatype as JSON on client side. – Sunny Gupta Feb 28 '12 at 17:41
  • @SAM there is no need, jQuery will guess it right i think (i'm no java expert though) – Nicola Peluchetti Feb 28 '12 at 20:54
2

use http://jsonlint.com/ to validate your output. your quotes are not valid.

{"name":"toto"} is ok

{'name':'toto'} is not
dweeves
  • 5,525
  • 22
  • 28