I have a rest web service like
@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);
}
And I use prototypejs javascript lib to invoke above rest web service from the client side with below code snippet.
<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>
Problem : I am not able to correctly pass the parameter to name and price of the service method.
I am passing two parameters in client but in service side only the parameter 'name' is getting mapped(that too with wrong value). when i print the name and price i get the following
System.out.println(name); ==> name='apple'&price=12
System.out.println(price); == null
How can i pass parameter to service from prototypejs client so that 'name' gets the value apple and 'price' gets the value 12.
put quotes around "name" ie
before
parameters: {name: 'apple', price: 12}
after
parameters: {'name': 'apple', 'price': 12}
'name' most likely is a keyword that is not getting passed correctly in the object
EDIT
More things to try...
make sure you are using the latest PrototypeJS version 1.7.1
add a comma after parameters: {name:'apple',price:12},
double check the browser is passing the parameters correctly using Chrome Dev Tools or Firebug - if they are being passed correctly then check your back end script
Ok finally it worked by modifying the 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>
Some options you might want to try:
Pass your parameters as a JS object transformed to a query string:
ajaxParameters = Object.toQueryString({ qkey: qValue });
where qkey and qValue are strings. In your Ajax.Request's second argument which is an object, use the resulting ajaxParameters as paramter value.
A PrototypeJS Hash object also works just fine most of the time:
ajaxParameters = $H({ qKey0: qValue0, qKey1: qValue2 [, ...] });
Whether or not the method is POST should not be a problem. Sometimes a POST method may also have an ACTION (url) with a "GET" variable like
http:
//mydomain.net/post.php?id=n&action=z
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.