1

Here is the scenario I have a REST service defined as follow:

@Path("/company/{companyName}/sessions")
public class RESTSessionController {

    RESTService service = new RESTService();
     @GET
     @Produces({"application/json"})
     @Path("/{username}/{password}") 
     public Result getFriend(@PathParam ("companyName") String companyName ,
             @PathParam ("username") String username,
             @PathParam ("password") String password){

         System.out.println(companyName);
         return service.login(username,password);
     }
}

To call this I have a javascript as follow:

$.ajax({
    url: 'http://localhost:8888/rest/company/hertz/sessions/amir/help',
    dataType: 'json',
    data: null,
    success: function(data) { 
        $("#abc").html(dumpObj(data,"Result",'',0));
         }
    });

This works fine and I get this back:

{"code":"200","description":"Amir is now logged in.","payload":{"@type":"xs:string","$":"Amir123"}}

which is perfectly fine.

Now I'm trying to go one step further and call my service using an object so I changed my code to:

$.ajax({
    qObj={username:"Amir",password:"123",companyName:"hertz"}
    url: 'http://localhost:8888/rest/company/',
    dataType: 'json',
    data: JSON.stringify(qObj),
    success: function(data) { 
        $("#abc").html(dumpObj(data,"Result",'',0));
         }
    });

And it won't work.

My question is simple, how to I call a REST service with parameter in the path (or without it) using jquery/javascript?

Thx for the help

Amir

4

2 回答 2

1

找到解决方案 如果您正在寻找相同的答案,这里是我的发现: 1) 您不能将路径中使用的用户变量作为发送到 REST 服务的对象的一部分。所以在我的情况下 {companyName} 不能真正作为 json 对象的一部分传递。2)在方法声明中,它必须是一个指示该方法需要一个 json 对象的指令,就是这种情况,所以我将代码更改为:

 @PUT
 @Produces(MediaType.APPLICATION_JSON)
 @Consumes(MediaType.APPLICATION_JSON)
 @Path("/")
 public API_Session login(API_Session_Request request){

一切都像一个魅力。

3) 在 javascript 中,您应该使用 JSON.stringify 您的对象:

var qObj={username:"Amir",password:"123",company_name:"hertz"}
$.ajax({
    type:'PUT',
    url: 'http://localhost:8888/rest/company/sessions',
    dataType: 'json',
    data: JSON.stringify(qObj),
    contentType: "application/json; charset=utf-8",
    success: function(data) { 
        $("#abc").html(dumpObj(data,"Result",'',0));
         }
    });

希望这可以帮助您节省一些时间。

于 2012-08-03T04:39:05.180 回答
0

为什么必须使用 JSON.stringify?试试这个,让我知道:)

$.ajax({
    url: 'http://localhost:8888/rest/company/',
    dataType: 'json',
    data: {username:"Amir",password:"123",companyName:"hertz"},
    success: function(data) { 
        $("#abc").html(dumpObj(data,"Result",'',0));
         }
    });
于 2012-08-01T16:24:34.817 回答