简体   繁体   中英

how to catch a value rendered from the controller in form of json in GSP page

I want to catch the value rendered from the controller checkWord() from gsp page in success function.I dont know how to do it.My code is as follows

<script>

   function callAjax(){
       var text= $('#word').val()

       console.log(text);
    $.ajax({

        url:"checkWord",
        type:"post",
        // dataType:'json',
        data:{text: text},

        success:function(){

            alert()
        }

    });
       console.log(data + "hello")
   }
</script>

Action

def checkWord(){
      def temp=params.text
      def query=Dictionary.findAllByWordLike(temp+'%');
      render query as JSON
}

Since you are using gsp for the views, I would let grails remoteFunction to manage the Ajax call.

First, the controller should have the "withFormat" closure so he knows how to render the data based on the way its called (in case it can be called later in a diferent way)

def checkWord(){
      def temp=params.text
      def query=Dictionary.findAllByWordLike(temp+'%');
      withFormat {
            json {  
                render query as JSON
            }
      }
}

Then from your gsp you call the controller action by the name checkWord.json and using remoteFunction

I placed your JQuery #word search as a param.

function callAjax(){
    ${remoteFunction(action: 'checkWord.json',
                   onSuccess: 'onSuccessFunction(data)',
                   params:'{text: \$(\'#word\').val()}' 
                  )
   }
}

Then you need a script function that it is going to be called when the ajax call succeed

   function onSuccessFunction(data){
        alert(data);
        //console.log(data + "hello")
    }

And that should work. (at least in the way I like to do it) Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM