如何将参数从prototypejs客户端传递给其他Web服务

时间:2013-02-13 18:01:21

标签: java javascript rest prototypejs

我有一个像

这样的休息网络服务
@Path("/postItem")
@Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
public Item postItem(@QueryParam("name") String name, @QueryParam("price") String price)
{
  System.out.println(name);
  System.out.println(price);
  return new Item(name , price);
}

我使用prototypejs javascript lib从客户端调用上面的休息Web服务,下面的代码片段。

<script>
  new Ajax.Request('/some_url', {
    method:'post',
    parameters: {name: 'apple', price: 12}
    onSuccess: function(transport) {
    var response = transport.responseText || "no response text";
    alert("Success! \n\n" + response);
    },
    onFailure: function() { alert('Something went wrong...'); }
 });
</script>

问题: 我无法正确地将参数传递给服务方法的名称和价格。

我在客户端传递了两个参数但在服务端只有参数'name'被映射(也是错误的值)。当我打印名称和价格时,我得到以下

 System.out.println(name);  ==> name='apple'&price=12
 System.out.println(price); == null

如何从prototypejs客户端传递参数到服务 这样'name'得到值apple,'price'得到值12.

3 个答案:

答案 0 :(得分:0)

在“名称”周围加上引号,即

    parameters: {name: 'apple', price: 12}

    parameters: {'name': 'apple', 'price': 12}

'name'最有可能是一个未在对象中正确传递的关键字

修改

更多的事情要尝试......

  • 确保您使用的是最新的PrototypeJS版本1.7.1

  • parameters: {name:'apple',price:12},

  • 之后添加逗号
  • 仔细检查浏览器是否正确使用Chrome开发工具或Firebug传递参数 - 如果正确传递参数,请检查后端脚本

答案 1 :(得分:0)

好吧最后它通过修改网址起作用了。

<script>
   new Ajax.Request('/some_url?name=apple&price=12', {
   method:'post',
   onSuccess: function(transport) {
   var response = transport.responseText || "no response text";
   alert("Success! \n\n" + response);
 },
   onFailure: function() { alert('Something went wrong...'); }
});
</script>

答案 2 :(得分:0)

您可能想尝试的一些选项:

将您的参数作为JS对象传递给查询字符串:

ajaxParameters = Object.toQueryString({ qkey: qValue });

其中qkey和qValue是字符串。在Ajax.Request的第二个参数中,它是一个对象,使用生成的ajaxParameters作为参数值。

PrototypeJS Hash对象在大多数情况下也可以正常工作:

ajaxParameters = $H({ qKey0: qValue0, qKey1: qValue2 [, ...]  });

该方法是否为POST应该不是问题。有时POST方法也可能有一个带有“GET”变量的ACTION(url),如

<击> HTTP: // mydomain.net/post.php?id=n&action=z