簡體   English   中英

允許表單發送 POST 請求但阻止頁面重新加載 - Javascript

[英]Allow form to send POST request but prevent page from reloading - Javascript


我正在處理一個帶有集成 v2 reCAPTCHA 的注冊表單,但我遇到了一個問題,即在提交包含 reCAPTCHA 的表單時,它正在重新加載頁面。 我有一個 php 函數來驗證 reCAPTCHA:
 if (isset($_POST['g-recaptcha-response'])) { function CheckCaptcha($userResponse) { $fields_string = ''; $fields = array( 'secret' =>' 6LcGWeEcAAAAAMALbpP873Pt40Wgwn6e0SuVn7EV', 'response' => $userResponse ); foreach($fields as $key=>$value) $fields_string .= $key . '=' . $value . '&'; $fields_string = rtrim($fields_string, '&'); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, 'https://www.google.com/recaptcha/api/siteverify'); curl_setopt($ch, CURLOPT_POST, count($fields)); curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string); curl_setopt($ch, CURLOPT_RETURNTRANSFER, True); $res = curl_exec($ch); curl_close($ch); return json_decode($res, true); } $result = CheckCaptcha($_POST['g-recaptcha-response']); if ($result['success']) { echo 'Success!'; } else { echo 'Error'; } }

當表單提交時,它會向它所在的頁面提供一個 POST 變量g-recaptcha-response ,因為表單沒有action屬性

所以,我需要獲取 POST 請求,但我不能讓頁面重新加載,因為這會刪除頁面上的其他數據。 我嘗試使用event.preventDefault(); 提交表單時,但這也阻止了表單提交 POST 變量。

我不知道如何通過 javascript 獲取 POST 變量,因為 reCAPTCHA 實際上不是輸入。

但是如果有一種方法可以通過 javascript 獲取 reCAPTCHA 的值,那么我可以使用 ajax 將 POST 請求發送到該函數。

如果在腳本 url 中包含查詢字符串:

<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"async defer></script>

那么你可以使用grecaptcha.getResponse因為它在谷歌 reCAPTCHA 文檔中說:
https://developers.google.com/recaptcha/docs/display

<script src="https://www.google.com/recaptcha/api.js?onload=onloadCallback&render=explicit"async defer></script>
<script type="text/javascript">
  var verifyCallBack = function(response) {
    alert(response);
  };
  var widgetId;
  var onloadCallback = function() {
    widgetId = grecaptcha.render('recaptcha', {
      'sitekey' : 's',
      'theme' : 'light'
    });
  }
</script>

<form>
  <div id="recaptcha"></div>
  <input type="submit" name="submit" value="submit">
</form>

$('form').submit(function(e) {
  e.preventDefault();
  var response = grecaptcha.getResponse(widgetId);
  $.ajax({
    url: 'validate_captcha.php',
    type: 'POST',
    data: {'g-recaptcha-response': response},
    success: function(data) {
      alert(data);
    },
    error: function(error) {
      alert(error);
    }
  });
});

然后在validate_captcha.php

<?php
if (isset($_POST['g-recaptcha-response'])) {
  function CheckCaptcha($userResponse) {
    $fields_string = '';
    $fields = array(
        'secret' => 'secret_key',
        'response' => $userResponse
    );
    foreach($fields as $key=>$value)
    $fields_string .= $key . '=' . $value . '&';
    $fields_string = rtrim($fields_string, '&');

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://www.google.com/recaptcha/api/siteverify');
    curl_setopt($ch, CURLOPT_POST, count($fields));
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, True);

    $res = curl_exec($ch);
    curl_close($ch);

    return json_decode($res, true);
  }
  $result = CheckCaptcha($_POST['g-recaptcha-response']);

  if ($result['success']) {
      echo 'success';

  } else {
     echo 'error';
  }
}
?>

因此,現在在您的 javascript 中,您可以在 if 語句中使用success:function(data)中的data變量:

if(data == 'success') {
  registerUser(name, email, password); // not a real function, just an example
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM