刷新页面如果渲染保存json成功为真

时间:2018-05-01 02:18:47

标签: java jquery grails groovy

控制器中的

if (!surveyMasterAnswerDetailInstance.save(flush: true)) {
    render([success: false, messages: surveyMasterAnswerDetailInstance.errors] as JSON)
    return
}    
    render([success: true] as JSON)
}

//在视图中

$(document).on('submit', '#creationOptionsForm', function(e){
  e.preventDefault();

  var form_data = new FormData($('#creationOptionsForm')[0]);

  var formURL = $(this).attr("action");
  $.ajax(
    {
        url : formURL,
        processData: false,
        contentType: false,
        async: false,
        cache: false,
        type: "POST",
        data : form_data,
       success: function(data){
           if(data.success == true){ // if true (1)
               setTimeout(function(){// wait for 5 secs(2)
               location.reload(); // then reload the page.(3)
              }, 5000); 
           }
        }
        ,
        error: function(jqXHR, textStatus, errorThrown)
        {
            //if fails     
        }
    });

   return true
});

1 个答案:

答案 0 :(得分:0)

完整的工作示例如下:

index.gsp中

<!DOCTYPE html>
<html>
<head>
    <meta name="layout" content="main">
    <script type="text/javascript">
            $(document).on('submit', function(e){
              e.preventDefault();

              $.ajax(
                {
                    url : "${g.createLink(controller:'testStuff', action:'jsonUrl')}",
                    processData: false,
                    contentType: false,
                    async: false,
                    cache: false,
                    type: "POST",
                    data : $('#creationOptionsForm').serialize(),
                    success: function(data, status, jqxhr) {
                        if ( jqxhr.responseJSON.success === true ){
                            setTimeout(function(){
                                location.reload();
                            }, 5000);
                        }
                    }
                    ,
                    error: function(jqXHR, textStatus, errorThrown)
                    {
                        alert( 'Failed' );
                    }
                });
            });
    </script>
</head>
<body>
<div>
    <g:form id="creationOptionsForm">
        <g:textField name="thename" value="${params.thename}" />
        <g:submitButton name="submit" value="submit" />
    </g:form>
</div>
</body>
</html>

TestStuffController

import grails.converters.JSON

class TestStuffController {

    def index() {
        println 'index'

    }

    def jsonUrl() {
        if (!true) {
            render([success: false, messages: 'bad stuff'] as JSON)
            return
        }
        render([success: true] as JSON)
    }
}

显然,上述条件是荒谬的,但所有的部分都是为了提供一个例子。