【问题标题】:Call Materialize javascript from Node.js从 Node.js 调用 Materialize javascript
【发布时间】:2016-10-17 07:16:56
【问题描述】:

我有一个表格供用户填写。在服务器端,我使用 mailgun 在表单提交后发送电子邮件。

出现错误时,我想显示一个 toast 对话框(Javascript 中的Materialize.toast("Error", 2500);)。由于错误检查发生在服务器端,我不知道如何调用该方法。

我碰巧在 HTML 中使用<script> 来阻止页面在提交时刷新——但我不知道如何处理这个<script> 中的错误。这里是:

<script type="text/javascript">
$("#contact-form").submit(function(e) {
    e.preventDefault(); // Prevents the page from refreshing
    var $this = $(this); // `this` refers to the current form element
    $.post(
        $this.attr("action"), // Gets the URL to sent the post to
        $this.serialize(), // Serializes form data in standard format

        function(data) {
        },
        "json" // The format the response should be in
    );
    Materialize.toast("Toasty McToastface!", 1000);
    $('#contact-form').trigger('reset');
});
</script>

感谢所有帮助。

【问题讨论】:

    标签: javascript html node.js materialize


    【解决方案1】:

    出现错误时,我想显示一个 toast 对话框(Materialize.toast("Error", 2500); in Javascript)。由于错误检查发生在服务器端,我不知道如何调用该方法。

    您必须从服务器端脚本返回错误,并检查成功回调中的 data 以查看是否有错误。

    $.ajax() 方法有一个错误回调($.post() 没有),但只有在超时、解析错误等情况下才会调用。

    你可以在客户端这样做:

    $.post(
        $this.attr("action"),
        $this.serialize(), 
        function(data) {
           if(data.error) {
              Materialize.toast("Toasty McToastface!", 1000);  
           }
        },
        "json" 
    );
    

    当然,要使其正常工作,服务器需要使用具有 error 属性的 JSON 对象进行响应,设置为 truefalse,具体取决于电子邮件是否已发送。

    如果您希望服务器能够在此回调之外与客户端通信,那么您可以使用 websockets(类似于 socket.io)

    【讨论】:

    • 所以我可以使用github.com/websockets/ws 并在服务器端出现错误时发送"error" 然后客户端会与之交互?
    • 是的,这也可以。我没有使用过那个库 (ws),但我过去使用过 socket.io,您可以在出现问题时简单地发出一个事件,然后在客户端捕获它并执行某些操作。
    • 服务器端发生了什么?因为我使用 Express,所以我对如何使用 socket.io 感到困惑。这是我处理表单提交的app.post()codeshare.io/XfCCQ
    • 实际上你可以通过使用 fail() 函数stackoverflow.com/questions/2833951/… 来跟踪 $.post 错误,你的服务器端应用程序必须返回一个 JSON 对象作为响应,如下所示:res.status(500).json({ error: 'message' });
    猜你喜欢
    • 2012-10-14
    • 2015-05-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-05
    相关资源
    最近更新 更多