2017-02-07 7 views
0

У меня есть страница gsp с двумя выпадающими списками. на основе значения i выберите и нажмите кнопку сравнения, он извлекает значение из базы данных и выполняет манипуляции. (например, сравнение), если они одинаковы на той же странице gsp, что и значение. Если они не совпадают, то значение должно отображаться на странице индекса gsp в двух текстовых областях рядом со значениями.Отображать данные в текстовой области страницы GSP

this is my gsp page 

    <!DOCTYPE html> 
<html> 
<head> 
<meta name="layout" content="main" /> 
<title>Json Compare</title> 

<g:javascript plugin="jquery" library="jquery" src="jquery/jquery-1.7.2.js"/> 
    <script> 
    $(document).ready(function(){ 
     $('.testMe').click(function(){ 
      var URL="${createLink(controller:'jsonComparison',action:'compare')}"; 
      alert(URL) 
      alert(firstText.value) 
      alert(secondText.value) 
      $.ajax({ 
       url:URL, 
       data: {firstText:firstText.value,secondText:secondText.value}, 
       success: function(data){ 
        //console.log(resp); 

        $("#result").val(data).show() 

       } 
      }); 
     }); 
    }); 

    </script> 


</head> 
<body> 
    <g:form> 
     <div></div><label>From Time</label><g:select name="firstText" from="${eventsList}" noSelection="['':'-Choose the From Date-']"/> 
     <label>To Time</label><g:select name="secondText" from="${eventsList}" noSelection="['':'-Choose the To Date-']"/></div> 
     <button class="testMe">Compare</button> 
     <br> 
     <textarea id="result" style="display: none"></textarea> 
     <%-- <textarea id="result1" style="display:none"></textarea> <textarea id ="result1" style="display:none"></textarea> --%> 
    </g:form> 
</body> 
</html> 

Это мой контроллер. на основе значения, выбранного на странице индекса, и нажмите кнопку сравнения. Я вызываю функцию ajax, которая вызывает контроллер. В контроллере я передаю выбранные значения и проверки из базы данных, нужно ли они такие же, и на основании ответа я, чтобы отобразить сообщение в index.gsp

class JsonComparisonController { 

    def preparedStatementService 


    def index() { 
     //List eventsList = preparedStatementService.retrieveValuesFromDb() 
     def eventsList = ['2017-10-11 04.94.34', '2016-09-11 04.94.44', '2017-10-12 04.94.89'] 
     render view: 'index', model: [eventsList: eventsList] 
    } 

    def compare() { 
     println "The Compare is called" 
     String firstParameter = params.firstText 
     String secondParameter = params.secondText 
     def returnValue 
     println "The first value is: " + firstParameter + "The second value is: " + secondParameter 
     if(firstParameter !=null && secondParameter !=null && firstParameter.length() > 0 && secondParameter.length() > 0){ 
      println "Both the values are not null" 
      if(firstParameter.equals(secondParameter)){ 
       println "First and second values are equal" 
       returnValue = "The Json are Equal and no MisMatch" 
       render status: 200, text: returnValue 
      }else{ 
       println "The values are not equal" 
       String value1 = "The First Json values" 
       String value2 = "The Second Json Values" 
       render status: 200, model:[firstText:value1,secondText:value2] 
      } 

     }else{ 
      render status: 200, text: "Please select the Time" 
     } 

    } 
} 

как я получить ответ от контроллера в функции ajax. а также отображать результат на странице index.gsp

ответ

0

Пожалуйста, изучить и понять исправления в GSP & контроллер это ваш GSP исправлено:

<!DOCTYPE html> 
<html> 
<head> 
<meta name="layout" content="main" /> 
<title>Json Compare</title> 
<g:javascript plugin="jquery" library="jquery" src="jquery/jquery-1.7.2.js"/> 
    <script> 
    $(document).ready(function(){ 
     $('.testMe').click(function(){ 
      var URL="${createLink(controller:'jsonComparison',action:'compare')}"; 
      alert(URL) 
      alert(firstText.value) 
      alert(secondText.value) 
      $.ajax({ 
       url:URL, 
       data: {firstText:firstText.value,secondText:secondText.value}, 
       success: function(data){ 
        if (data.status===true) { 
        //notice .html since it is content of textArea 
        $('#result1').html(data.result) 
        //if this was <input type=text value="something" 
        //then result would be the value of the form field 
        //$('#result1').val(data.result) 
        } else { /// if (data===false) { 
         $('#result1').html(data.value1).show() 
         $('#result2').html(data.value2).show() 
        } 
       } 
      }); 
     }); 
    }); 
    </script> 
</head> 
<body> 
    <g:form> 
     <div></div><label>From Time</label><g:select name="firstText" from="${eventsList}" noSelection="['':'-Choose the From Date-']"/> 
     <label>To Time</label><g:select name="secondText" from="${eventsList}" noSelection="['':'-Choose the To Date-']"/></div> 
     <button class="testMe">Compare</button> 
     <br> 
     <textarea id="result" style="display: none"></textarea> 
     <%-- <textarea id="result1" style="display:none"></textarea> <textarea id ="result1" style="display:none"></textarea> --%> 
    </g:form> 
</body> 
</html> 

Здесь контроллер фиксируется

class JsonComparisonController { 

    def preparedStatementService 


    def index() { 
     //List eventsList = preparedStatementService.retrieveValuesFromDb() 
     def eventsList = ['2017-10-11 04.94.34', '2016-09-11 04.94.44', '2017-10-12 04.94.89'] 
     render view: 'index', model: [eventsList: eventsList] 
    } 

    def compare() { 
     String firstParameter = params?.firstText //make it nullsafe not going to throw an exception with ? 
     String secondParameter = params?.secondText 
     def returnValue 
     //this is doing exactly what you were doing long winded 
     def reply 
     if(firstParameter && firstParameter) { 
      if (firstParameter == firstParameter){ 
       reply=[status:true, result:"The Json are Equal and no MisMatch"]     
      }else{ 
       reply = [status:false, value1:"The First Json values ${firstParameter}", value2:"The Second Json Values ${secondParameter}"]    
      } 
     }else{ 
      reply = [status:false, value1:"issue here", value2:"issue here"]  
     } 
     render status: 200, text:(reply as JSON).toString() 
    } 
} 

И вместо того, чтобы нажимать на кнопку, вы могли бы указать

$('#secondText').on('change', function() { 

var val = $(this).val(); 
var other = $('#firstText').val(); 
    if (val!='' && other!='') { 
var URL="${createLink(controller:'jsonComparison',action:'compare')}"; 
       alert(URL) 
       alert(val) 
       alert(other) 
       $.ajax({ 
        url:URL, 
        data: {firstText:val,secondText:other}, 
        success: function(data){ 
         if (data.status===true) { 
         //notice .html since it is content of textArea 
         $('#result1').html(data.result) 
         //if this was <input type=text value="something" 
         //then result would be the value of the form field 
         //$('#result1').val(data.result) 
         } else { /// if (data===false) { 
          $('#result1').html(data.value1).show() 
          $('#result2').html(data.value2).show() 
         } 
        } 
       }); 
    } 
}) 

это автоматически срабатывает при смене второго поля

+0

моя проблема в том, что мне нужно отобразить результат на той же странице gsp. Если они не равны, они должны отображаться в двух отдельных текстовых областях бок о бок –

+0

, как только я получаю ответ от контроллера, что значения не равны, а текстовая область должна быть видимой, и она должна печатать обе значения –

+0

, я попробовал код, который вы упомянули выше, но теперь моя текстовая область не отображается –

 Смежные вопросы

  • Нет связанных вопросов^_^