我正在尝试在我的MVC网站中实现reCAPTCHA,但除非我从表单提交,否则它不会验证,如下所示:
@using(Html.BeginForm("VerifyCaptcha", "Signup") )
{
@ReCaptcha.GetHtml(theme: "clean", publicKey: "6LcnfAITAAAAAAY--6GMhuWeemHF-rwdiYdWvO-9");
<input type="submit" id="btnVerify" value="Verify" />
}
[HttpPost]
public ActionResult Index(PolicyModel model)
{
var result = ReCaptcha.Validate(privateKey: "THE_KEY");
return View();
}
我不想使用表单提交,因为我不想返回新视图。我的所有数据都以json形式的ajax推动。我想做的是:
$.ajax({
url: 'verifyCaptcha',
dataType: 'json',
contentType: "application/x-www-form-urlencoded",
type: "POST",
async: false,
success: function (response) {
alert(response);
},
error: function(response) {
alert('There was a problem verifying your captcha. Please try again.');
}
});
return valid;
[HttpPost]
public ActionResult VerifyCaptcha()
{
var result = ReCaptcha.Validate(privateKey: "THE_KEY");
return Json(result);
}
ajax调用到达控制器,但Validation方法立即完成,几乎就像它甚至没有发出请求一样。我不确定如果验证码不在表格中,为什么验证总是失败 - 它是否可能丢失信息,如公钥或其他东西?有解决方法吗?
编辑:添加了没有模型的ajax控制器操作方法。
答案 0 :(得分:1)
只需使用serializeArray()或serialize()并将您的ajax请求更改为
$.ajax({
url: 'verifyCaptcha',
dataType: 'json',
contentType: "application/x-www-form-urlencoded",
type: "POST",
async: false,
data: $('form').serializeArray(), // $('form').serialize(),
success: function (response) {
alert(response);
}
});
您尚未在请求中添加数据部分。这似乎是问题
答案 1 :(得分:0)
您需要使用表单请求的所有参数设置Ajax请求。例如,内容类型为application/x-www-form-urlencoded
。
看看这个:application/x-www-form-urlencoded or multipart/form-data?
更新:
......是的......你必须做一个POST请求,而不是GET。
更新:
$.ajax({
url: 'verifyCaptcha',
contentType: "application/x-www-form-urlencoded",
type: "POST",
success: function (response) {
alert(response);
},
error: function(response) {
alert('ERROR', response);
}
});