2017-04-04 104 views
1

我想使用Google Invisible reCAPTCHA,但它發送空的g-recaptcha-response POST參數時,我在同一頁中有多個窗體。這裏是我的代碼:隱形reCAPTCHA發送多種形式的空g-recaptcha響應

谷歌JS

<script src="//google.com/recaptcha/api.js?hl=pt-BR&onload=captchaCallback&render=explicit" async defer></script> 

表1

<form action="/site/Contact/send" id="form1"> 
    <input type="text" name="nome" required> 

    <div class="g-recaptcha" 
     data-sitekey="xxxxxxxxxxxxxxxxxxxxxxxx" 
     data-callback="form1Callback" 
     data-size="invisible"> 
    </div> 

    <button type="submit">Send</button> 

</form> 

表2

<form action="/site/Contact/send" id="form2"> 
    <input type="text" name="nome" required> 

    <div class="g-recaptcha" 
     data-sitekey="xxxxxxxxxxxxxxxxxxxxxxxx" 
     data-callback="form2Callback" 
     data-size="invisible"> 
    </div> 

    <button type="submit">Send</button> 
</form> 

我JS(上this answer如下基於]

$(document).ready(function() { 

    window.captchaCallback = function(){ 
     $('.g-recaptcha').each(function(index, el) { 
      var attributes = { 
       'sitekey' : $(el).data('sitekey'), 
       'size'  : $(el).data('size'), 
       'callback' : $(el).data('callback') 
      }; 

      grecaptcha.render(el, attributes); 
     }); 
    }; 

    window.form1Callback = function(){ 
     $('#form1').submit(); 
    }; 

    window.form2Callback = function(){ 
     $('#form2').submit(); 
    }; 
}); 

當我提交的這些形式的g-recaptcha-response參數發送空單,。

enter image description here

有人可以幫助我把它的工作嗎?

+0

如果答案解決了您的問題,請將其標記爲您接受的答案。這樣世界其他地方就知道哪種解決方案適用於您的特定情況。 – Aram

+1

@Aram,你是對的,但沒有答案能夠解決這個問題,我在這個時候每頁使用單個表單 –

回答

0

根據文件和你的代碼,我猜你試圖使用Programmatically invoke the challenge.Google reCaptcha。 所以在您的JS代碼你錯過了一個聲明:

grecaptcha.execute();

UPDATE 也許我誤解你的問題,所以檢查:

呈現明確的onload可選。是否顯式渲染小部件 。默認爲onload,它將呈現它找到的第一個g-recaptcha標記的 小部件。

據我瞭解,它只是發現第一個標記標籤,並導致您的問題?

+0

默認的'onload'只在它找到的第一個標籤中呈現'g-recaptcha',因爲這個我改爲'explicit',這樣我可以加載兩個元素 –

1

如果您在div元素中渲染不可見的recaptcha,您將需要手動調用grecaptcha.execute()來運行recaptcha。另外,如果存在多個帶​​有recaptcha的表單,那麼當調用grecaptcha.render()方法時,需要使用爲每個recaptcha生成的小部件ID調用grecaptcha.execute()方法。

$(document).ready(function() { 
    window.captchaCallback = function(){ 
     $('.g-recaptcha').each(function(index, el) { 
      var attributes = { 
       'sitekey' : $(el).data('sitekey'), 
       'size'  : $(el).data('size'), 
       'callback' : $(el).data('callback') 
      }; 

      $(el).data('recaptcha-widget-id', grecaptcha.render(el, attributes)); 
     }); 
    }; 

    window.form1Callback = function(){ 
     $('#form1').data("recaptcha-verified", true).submit(); 
    }; 

    window.form2Callback = function(){ 
     $('#form2').data("recaptcha-verified", true).submit(); 
    }; 

    $('#form1,#form2').on("submit", function(e){ 
     var $form = $(this); 
     if ($form.data("recaptcha-verified")) return; 

     e.preventDefault(); 
     grecaptcha.execute($form.find(".g-recaptcha").data("recaptcha-widget-id")); 
    }); 
});