开发者

How to display a message box in view from controller?

开发者 https://www.devze.com 2023-04-03 16:29 出处:网络
After a user enters some numbers and other data on a form a total is calculated.The user might also choose to enter a discount amount.I use a jQuery AJAX method to send all the data to the getT开发者_

After a user enters some numbers and other data on a form a total is calculated. The user might also choose to enter a discount amount. I use a jQuery AJAX method to send all the data to the getT开发者_如何学JAVAotal method in the Load controller. If the user entered a discount amount greater than the calculated total I want a message box to pop up (similar to a JavaScript alert box) saying the discount must be less than the total. Is there any clean way to do this from the controller?


No. You'd want to send a result back in your ajax response that tells the client to display your message box. Then you'd probably use JavaScript to show it. There are a lot of jQuery plugins for displaying message boxes. For example: jQueryUI's Dialog.


Here is what I did. In my view I have the following code in one of my JavaScript methods. I use jQuery's getJSON instead of ajax because it seemed to fit better (cleaner).

$.getJSON(
  "/truckingmanagement/load/getTotal",
  {cargoSource:cargoSource, cargo:cargo, haulRate:haulRate, tonnage:tonnage, mileage:mileage, discount:discount, taxExempt:taxExempt},
  function(result) {
    if(result.message != null){
      alert(result.message);
      $("#discount").val("");
      $("#totalCell").html(result.total);
    }
    else{
      $("#totalCell").html(result.total);
    }
  });

I my controller I still used the render method inside my closure, but modified it for JSON, making sure to import grails.converters.*.

render(contentType:"text/json") {
    total = g.textField(name: 'total', value: totalBill, readonly: 'readonly')
    message = errorMessage
}

The totalBill value has been calculated prior to calling render, and errorMessage is just a string that contains a message based on what the error was (negative discount value or discount value greater than total) or no message at all. Thus if the message is null no message will be displayed.


I think it is technically possible to have your controller generate javasacript as response to an ajax call, but that'd be a very ugly way to do it.

Better is to send JSON. Something like:

result = []
result.success = total >= discount
result.total = total
render result as JSON

And in the Ajax call, check for success, show the total if successful, show the message if not.

0

精彩评论

暂无评论...
验证码 换一张
取 消