简体   繁体   English

允许表单发送 POST 请求但阻止页面重新加载 - Javascript

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


I am working on a signup form with an integrated v2 reCAPTCHA and I ran into the issue that when submitting the form which includes the reCAPTCHA, it is reloading the page. 我正在处理一个带有集成 v2 reCAPTCHA 的注册表单,但我遇到了一个问题,即在提交包含 reCAPTCHA 的表单时,它正在重新加载页面。 I have a php function to validate the 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'; } }

When the form submits it gives a POST variable g-recaptcha-response to the page it's on as there is no action attribute to the form当表单提交时,它会向它所在的页面提供一个 POST 变量g-recaptcha-response ,因为表单没有action属性

So, I need to get the POST request but I can't let the page reload because that would get rid of other data on the page.所以,我需要获取 POST 请求,但我不能让页面重新加载,因为这会删除页面上的其他数据。 I tried using event.preventDefault();我尝试使用event.preventDefault(); when the form is submitted, but that also prevented the form from submitting the POST variable.提交表单时,但这也阻止了表单提交 POST 变量。

I have no idea how I would get the POST variable through javascript because the reCAPTCHA is not actually an input.我不知道如何通过 javascript 获取 POST 变量,因为 reCAPTCHA 实际上不是输入。

But if there was a way to get the value of the reCAPTCHA through javascript, then I could use ajax to send the POST request to the function.但是如果有一种方法可以通过 javascript 获取 reCAPTCHA 的值,那么我可以使用 ajax 将 POST 请求发送到该函数。

If you include the query strings in the script url:如果在脚本 url 中包含查询字符串:

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

then you can use grecaptcha.getResponse as it says in the google reCAPTCHA documentation:那么你可以使用grecaptcha.getResponse因为它在谷歌 reCAPTCHA 文档中说:
https://developers.google.com/recaptcha/docs/display 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);
    }
  });
});

And then in validate_captcha.php :然后在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';
  }
}
?>

So now in your javascript, you can use the data variable inside success:function(data) in an if statement:因此,现在在您的 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.

相关问题 没有按钮时,如何防止获取请求重新加载 Javascript 中的页面? - How to prevent a fetch request from reloading the page in Javascript when there is not a button? 如何防止多文档表单页面重新加载? - How to prevent multidocument form page from reloading? 防止表单提交后重新加载页面 - prevent page from reloading after form submit 浏览器重新加载页面时,如何从chrome扩展程序(无需单击)向flask发送POST请求? - How to send POST request from chrome extension (without clicking) to Flask when browser is reloading the page? 如何防止页面在 JavaScript 获取帖子请求后刷新? - How to prevent page from refreshing after JavaScript fetch post request? 发布请求而无需重新加载页面,并且不支持JavaScript(Node Express框架) - Post request without reloading page and support for no javascript (Node Express framework) 使用JavaScript阻止刷新/重新加载页面 - Prevent refreshing / reloading a page with JavaScript 如何防止ajax请求重新加载页面 - How can i prevent ajax request from reloading page 发布表单后如何防止页面重新加载? - How can I prevent the page from reloading after posting a form? 如何防止页面在表单提交后重新加载 - JQuery - How to prevent page from reloading after form submit - JQuery
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM