如何将参数从prototypejs客户端传递到rest web服务

How to pass parameter from prototypejs client to rest web service

本文关键字:rest web 服务 客户端 参数 prototypejs      更新时间:2023-09-26

我有一个类似的rest web服务

@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从客户端调用上面的rest 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。

在"name"(即)周围加引号

之前

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

之后

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

"name"很可能是在对象中未正确传递的关键字

编辑

还有更多的尝试。。。

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

  • parameters: {name:'apple',price:12}, 后添加逗号

  • 仔细检查浏览器是否使用Chrome开发工具或Firebug正确地传递了参数-如果它们传递正确,则检查您的后端脚本

好的,通过修改url终于成功了。

<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>

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

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

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

其中qkey和qValue是字符串。在您的Ajax中。请求的第二个参数是一个对象,使用得到的ajaxParameters作为参数值。

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

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

该方法是否为POST应该不是问题。有时POST方法也可能有一个ACTION(url),其中包含类似的"GET"变量

http://mydomain.net/post.php?id=n&action=z