在Yesod中没有刷新页面的POST请求

时间:2018-01-05 21:25:28

标签: ajax post yesod page-refresh yesod-forms

任务是创建一个具有漂亮错误处理的注册表单 我是Yesod的新手,所以我发现这样做的唯一方法是:

regForm :: Form User

getRegRExtra extraFormWidget = do
  (formWidget, enctype) <- case extraFormWidget of
                             Nothing -> generateFormPost regForm
                             Just val -> return val
  defaultLayout $ $(widgetFile "reg/reg")

getRegR = getRegRExtra Nothing

postRegR = do
  ((result, widget), enctype) <- runFormPostNoToken regForm 
  case result of
    FormSuccess person -> undefined
    _ -> getRegRExtra (Just (widget, enctype))

但是有一个问题:每次提交时页面都会刷新,而我希望它动态地执行此操作 我知道它可以在Ajax或Jquery的帮助下修复,
但是,在使用Yesod POST功能时,我将失去所有的好处 有没有标准的方法来解决这个问题?

1 个答案:

答案 0 :(得分:0)

解决方案是:

-- Used for returning plain html as AJAX response.
noLayout :: Widget -> Handler Html
noLayout widget = do
  pc <- widgetToPageContent widget
  withUrlRenderer [hamlet| ^{pageBody pc} |]

-- Replace a default event handler with the AJAX one.
getRegR :: Handler Html
getRegR = do
  ((res, formWidget), enctype) <- runFormPost regForm
  defaultLayout $ do
    $(widgetFile "reg/reg")
    addScriptRemote "https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"
    toWidget [julius|
      $(document).on('click', '.btn-important', function(e) {
        e.preventDefault();
        e.stopPropagation();
        $.ajax({
          type: 'POST',
          url:'@{RegR}',
          cache: false,
          dataType: 'html',
          data:$('#form-reg').serialize(),
          success: function(data) { $('#form-reg').html(data); }
        });
      }); |]

postRegR :: Handler Html
postRegR = do
  ((result, widget), enctype) <- runFormPostNoToken regForm
  noLayout widget