[英]Call Materialize javascript from Node.js
我有一個供用戶填寫的表格。 在服務器端,提交表單后,我正在使用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>
我感謝所有幫助。
發生錯誤時,我想顯示一個Toast對話框(在Javascript中為Materialize.toast(“ Error”,2500);)。 由於錯誤檢查是在服務器端進行的,因此我不確定如何調用該方法。
您必須從服務器端腳本返回錯誤,並檢查成功回調中的data
以查看是否存在錯誤。
$.ajax()
方法具有錯誤回調( $.post()
沒有錯誤回調),但是僅在存在超時,解析錯誤等情況下才調用。
您可以在客戶端上這樣做:
$.post(
$this.attr("action"),
$this.serialize(),
function(data) {
if(data.error) {
Materialize.toast("Toasty McToastface!", 1000);
}
},
"json"
);
當然,要使其正常工作,服務器將需要使用具有error
屬性的JSON對象進行響應,該JSON對象根據是否發送電子郵件而設置為true
或false
。
如果您希望服務器能夠在此回調之外與客戶端進行通信,則可以使用websockets(類似於socket.io)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.