Reputation: 679
I'd like to send a data from my javascript to my struts action. It's just an id, therefore i wonder if there is a better way than to do it through a form.submit();
here is the variable i'd like to send.
var id = $('[data-detailsid="' + $(this).data('headid') + '"]');
What would be the proper way to do it ?
My current js function :
$.ajax({
url: "deleteProduct",
type: 'POST',
data: 'productId=' + id
});
And my struts action :
@Action("/deleteProduct")
@ResultPath("/")
@Result(name = "success", location = "jsp/board.jsp")
public class DeleteAction {
int productId;
@Autowired
private UserDao userDao;
public String execute() {
Product currentProduct = new Product();
currentProduct.setId(productId);
userDao.deleteProduct(currentProduct);
setProducts(userDao.getProducts());
return "success";
}
public void setProductId(int productId) {
this.productId = productId;
}
}
Upvotes: 1
Views: 984
Reputation: 1
If you are calling action via Ajax, there isn't necessary to return dispatcher
result. You can return result type json
if you have json plugin on the classpash and @ParentPackage("json-default")
annotation to the action. You can use root
parameter to the json result to define the object being serialized when result is executed. By default the root
is set to the action instance, so all properties are serialized. If you want to restrict/allow some properties from json serialization you can use parameters to the result excludeProperties
and includeProperties
. Both parameters are mutually exclusive.
@Result(type="json", params = {"includeProperties", "productId" })
It will return productId
back to the page if it was populated to the action bean and the action class has a getter method.
You can get the result on success callback function using
$.ajax({
url: "deleteProduct",
type: 'POST',
data: 'productId=' + id,
dataType: "json"
}).done(function(data){
console.log("The product id:" + data.productId);
}).fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
Upvotes: 4