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

后端 未结 3 1256
离开以前
离开以前 2021-01-15 03:09

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         


        
相关标签:
3条回答
  • 2021-01-15 03:19

    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");
                            }
                        });
                    }
    
    
    0 讨论(0)
  • 2021-01-15 03:28

    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);  
           }  
         });
    
    0 讨论(0)
  • 2021-01-15 03:46

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

    {"name":"toto"} is ok
    
    {'name':'toto'} is not
    
    0 讨论(0)
提交回复
热议问题