如何在控制器视图中显示消息框?
用户在表单上输入一些数字和其他数据后,就会计算出总计。用户还可以选择输入折扣金额。我使用 jQuery AJAX 方法将所有数据发送到 Load
控制器中的 getTotal
方法。如果用户输入的折扣金额大于计算出的总额,我希望弹出一个消息框(类似于 JavaScript alert
框),说明折扣必须小于总额。有没有什么干净的方法可以从控制器执行此操作?
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 getTotal
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不。您需要在 ajax 响应中发送回结果,告诉客户端显示您的消息框。然后您可能会使用 JavaScript 来显示它。有很多用于显示消息框的 jQuery 插件。例如:jQueryUI 的对话框。
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.
这就是我所做的。在我看来,我的 JavaScript 方法之一中有以下代码。我使用 jQuery 的
getJSON
而不是ajax
因为它似乎更适合(更干净)。在我的控制器中,我仍然在闭包中使用
render
方法,但将其修改为 JSON,确保import grails.converters.*
。totalBill
值是在调用render
之前计算出来的,而errorMessage
只是一个字符串,其中包含基于错误内容的消息(负数)折扣值或折扣值大于总计)或根本没有消息。因此,如果消息为null
,则不会显示任何消息。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 ofajax
because it seemed to fit better (cleaner).I my controller I still used the
render
method inside my closure, but modified it for JSON, making sure toimport grails.converters.*
.The
totalBill
value has been calculated prior to callingrender
, anderrorMessage
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 isnull
no message will be displayed.我认为从技术上讲,让控制器生成 javasacript 作为对 ajax 调用的响应是可能的,但这是一种非常丑陋的方法。
更好的是发送 JSON。类似于:
在 Ajax 调用中,检查是否成功,如果成功则显示总数,如果失败则显示消息。
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:
And in the Ajax call, check for success, show the total if successful, show the message if not.